如何修改类中的值? (C ++)

时间:2015-04-25 03:49:55

标签: c++

我只是尝试从主文件中添加或减去类中的值,但似乎总是重置此值。作为初学者,我真的不明白为什么?!每当我打印player.worldPositionY时,它会显示 -1 1 0 (如果未选择1或2 - moveForward或moveBack)

我有两个简单的文件,Main.cpp:

#include <iostream>
#include "player.h"

using namespace std;

int keyboardInput;

int main()
{
    Player player;

    cin.get();
    cin >> keyboardInput;

    if (keyboardInput == 1){
        player.moveForward();
    } else if (keyboardInput == 2){
        player.moveBack();
    }

    cout << "Y: " << player.worldPositionY << endl;
    main();
}

还有一个玩家:

class Player {
public:
    int worldPositionY = 0;

    void moveForward();
    void moveBack();
};

void Player::moveForward(){worldPositionY += 1;}

void Player::moveBack(){worldPositionY -= 1;}

我显然遗漏了一些东西。请帮忙!

2 个答案:

答案 0 :(得分:6)

您以递归方式呼叫main。你不想这样做,而是这样做:

int main()
{
    Player player;

    while (true)
    {
        cin.get();
        cin >> keyboardInput;

        if (keyboardInput == 1){
            player.moveForward();
        } else if (keyboardInput == 2){
            player.moveBack();
        }

        cout << "Y: " << player.worldPositionY << endl;
    }
}

递归调用main表示每次输入值时都会重新创建player个对象,这就是为什么您的值始终为-11

答案 1 :(得分:0)

问题是每次调用main()时,都会再次使用默认值零创建对象。现在,你可以像his answer中所说的@cmbasnett那样做,或者你可以像worldPositionY static一样做

class Player {
public:
    static int worldPositionY;   // making it static 

    void moveForward();
    void moveBack();
};
int Player::worldPositionY=0;  // don't forget to initialize it outside as well.