gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:24:07 24 4
gpt4 key购买 nike

我只是想从主文件中添加或减去类中的值,但它似乎总是将此值重置为。作为初学者,我真的不明白为什么?!每次我打印 player.worldPositionY 时,它都会显示 -110(如果未选择 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();
}

还有一个播放器.h:

class Player {
public:
int worldPositionY = 0;

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

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

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

我显然遗漏了什么。请帮忙!

最佳答案

您正在递归调用 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

关于c++ - 如何修改类中的值? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com