使用类getter函数C ++的奇怪输出

时间:2016-03-29 15:13:07

标签: c++ oop getter-setter

所以我在头文件中有这个用于飞镖游戏的代码:

    class Player
    {
    private:
        string playerName;
        int bullAccuracy;
        int outerAccuracy;
        int singleAccuracy;
    public:

        //getters
        string& getName();
        int& getBullAccuracy();
        int& getSingleAccuracy();

        //setters
        void setName(string& name);
        void setBullAccuracy(int& bull_accuracy);
        void setSingleAccuracy(int& single_accuracy);
    };

然后.cpp文件中的对应getter和setter函数如下所示:

    //getters
    string& Player::getName()
    {
        return playerName;
    }
    unsigned int& Player::getScore()
    {
        return playerScore;
    }
    int& Player::getBullAccuracy()
    {
        return bullAccuracy;
    }
    int& Player::getSingleAccuracy() 
    {
        return singleAccuracy;
    }

//setters
void Player::setName(string& name)
{
    playerName = name;
}
void Player::setBullAccuracy(int& bull_accuracy)
{
    bullAccuracy = bull_accuracy;
}
void Player::setSingleAccuracy(int& single_accuracy)
{
    singleAccuracy = single_accuracy;
}

所有这些非常简单和基本的getter / setter代码都适用于类数据,对吧?

在main()函数中,我为我的玩家设置名称,各种准确度,然后通过getter显示它们。所有这些都是使用对象和迭代器的向量完成的,如下所示:

vector<Player> player(2);
vector<Player>::iterator modIter;
int bAccuracy, sAccuracy;
string playerName;
cout << "Input the name of the players: " << endl;
for (modIter = player.begin(); modIter != player.end(); modIter++)
{
    cin >> playerName;
    modIter->setName(playerName);
}
cout << "\nSet the players' bull accuracy:" << endl;
for (modIter = player.begin(); modIter != player.end(); modIter++)
{
    cout << modIter->getName() << ": ";
    cin >> bAccuracy;
    modIter->setBullAccuracy(bAccuracy);
}
cout << "\nSet the players' single hit accuracy: " << endl;
for (modIter = player.begin(); modIter != player.end(); modIter++)
{
    cout << modIter->getName() << ": ";
    cin >> sAccuracy;
    modIter->setBullAccuracy(sAccuracy);
}
//display values to check program working well so far
for (modIter = player.begin(); modIter != player.end(); modIter++)
{
    cout << modIter->getBullAccuracy() << endl;
    cout << modIter->getOuterAccuracy() << endl;
    cout << modIter->getSingleAccuracy() << endl;
}

运行代码后,输入输入&#34; Joe&#34;和&#34; Sid&#34;对于名称,分别为71和73的公牛准确度,然后对于单人命中准确度为80,这就是我的控制台输出:

输入玩家姓名:

西特

设置玩家的公牛准确度:

乔:71:

Sid:73 //这意味着至少名字设置正确

设置玩家的单击命中率:

乔:80:

希德:80

//这里是奇怪的输出

80 //这应该是71

-842150451 //这80

80 //这里是73

-842150451 //再来一次80

那究竟发生了什么,因为这是基本和熟悉的getter和setter的使用,我不知道如何自己调试,因为我没有看到问题。我的代码中是否有某些内容可以让我发现这会改变结果?

非常感谢您的帮助

1 个答案:

答案 0 :(得分:6)

当您提示单一准确度时,您仍然在调用setBullAccuracy方法,而不是setSingleAccuracy。你也没有初始化你的成员变量,这就是为什么打印singleAccuracy给你带来垃圾。