用C ++设置函数不起作用

时间:2016-07-05 16:43:38

标签: c++

我在这里完全是新手,所以请原谅。 由于我没有得到结果,我希望我会在这里发布整个代码。

class DigitalPet
{
public:
    DigitalPet (std::string );
    ~DigitalPet ();
    void talk ();
    void play ();
    void feed ();
    void setMemberName ( std::string );
    void setMemberMood ();
    std::string getMemberMood () const;
    int getMemberHunger () const;
    int getMemberBoredom () const;


private:
    std::string m_memberName;
    int m_memberHunger;
    int m_memberBoredom;
    std::string m_memberMood;
};

实现。

DigitalPet::DigitalPet(std::string name)
{
    setMemberName (name);
    m_memberHunger = 8;
    m_memberBoredom = 4;
    setMemberMood();
}
DigitalPet::~DigitalPet()
{

};
void DigitalPet::talk()
{
    std::cout << "\nHello. My name is " << m_memberName << " and I am " << getMemberMood()<< std::endl;
    m_memberHunger -= 2;
    m_memberBoredom -= 2;
}
void DigitalPet::play()
{
    m_memberHunger -= 4;
    m_memberBoredom -= 2;
}
void DigitalPet::feed()
{
    m_memberHunger += 4;
    m_memberBoredom -= 1;
}
void DigitalPet::setMemberName ( std::string name)
{
    while (name.length() > 10 )
    {
        std::cout << "The name you entered is too long. Please enter a smaller name!!!" << std::endl;
        std::cin >> name;

    }
    m_memberName = name;
}
void DigitalPet::setMemberMood()
{

    if (m_memberHunger <= 0 && m_memberBoredom <= 0 )
   {
       m_memberMood = "mad";
    }
   else if (m_memberHunger > 0 && m_memberHunger <= 4 && m_memberBoredom > 0 && m_memberBoredom <= 2)
   {
       m_memberMood = "frustrated";
  }
    else if (m_memberHunger > 4 && m_memberHunger <= 8 && m_memberBoredom > 2 && m_memberBoredom <= 4)
    {
        m_memberMood = "good";
    }
    else if (m_memberHunger > 8 && m_memberHunger <= 12 && m_memberBoredom > 4 && m_memberBoredom <= 6)
{
        m_memberMood = "happy";
}
}
std::string DigitalPet::getMemberMood() const
{
    return m_memberMood;
}
int DigitalPet::getMemberHunger() const
{
    return m_memberHunger;
}
int DigitalPet::getMemberBoredom() const
{
    return m_memberBoredom;
}

我打电话给他们。

int main()
{
    DigitalPet Yama("Yama");

    Yama.talk();

    std::cout << Yama.getMemberBoredom()<< std::endl;

    std::cout << Yama.getMemberHunger() << std::endl;

    Yama.talk();

    return 0;
}

现在的问题是,尽管m_memberHunger和m_memberBoredom减少,但它继续输入心情“好”。

2 个答案:

答案 0 :(得分:7)

现在是学习如何使用调试器的时候了。

如果您的setMemberName方法从一开始就具有正确的长度,则永远不会设置该名称。只有错误才会触发成员变量的实际设置。

答案 1 :(得分:3)

问题在于函数本身,在这里它被修改:

void DigitalPet::setMemberName ( std::string name)
{
    while (name.length() > 10 )
    {
        std::cout << "The name you entered is too long. Please enter a smaller name!!!" << std::endl;
        std::cin >> name;
    }

    m_memberName = name;
}

问题是你只在参数超过10个字符时指定了一个名字而且你没有再次检查它,只是分配了它。