[英]Passing a variable from main into a public class function?
I was wondering how in this situation I can pass a variable from main into a public class function. 我想知道在这种情况下如何将变量从main传递给公共类函数。 In this situation the health variable doesn't change at all even though it should. 在这种情况下,健康变量根本不会更改,即使它应该更改。 Here's my code: 这是我的代码:
class PlayerCharacter
{
public:
void SetHealth(int Health)
{
m_health = Health;
}
int GetHealth()
{
return m_health;
}
private:
int m_health;
int m_maxhealth;
};
int main()
{
PlayerCharacter PC;
bool playing = true;
int Choice;
int v1;
int v2;
while (playing)
{
PrintMainMenu();
cout << "Set Health And Max Health" << endl;
cin >> Choice;
v1 = Choice;
cin >> Choice;
v2 = Choice;
PC.SetHealth(v1);
PC.SetMaxHealth(v2);
system("CLS");
}
return 0;
}
Is there something I'm missing here? 我在这里想念什么吗? Thanks. 谢谢。
edit: All of my code 编辑: 我所有的代码
From your code link, your PrintMainMenu()
function is creating an entirely new Character
each time. 通过代码链接,您的PrintMainMenu()
函数每次都会创建一个全新的Character
。 It has no relation to the one being edited in main()
. 它与main()
正在编辑的内容无关。
You should change it to accept a Character
as a reference and use that to print your stats: 您应该更改它以接受Character
作为参考,并使用该Character
来打印统计信息:
void PrintMainMenu(Character& PC) {
...
}
You can try using getline (cin, input) instead of cin>> as reading directly with cin is not type safe and as far as I know, it does not remove newline character. 您可以尝试使用getline(cin,input)代替cin >>,因为直接用cin读取不是安全的类型,据我所知,它不会删除换行符。 Also, it does not perform length check. 另外,它不执行长度检查。 So it has been some time not to use C++ but if I remember correctly getline works better. 因此,已经有一段时间不使用C ++了,但是如果我记得正确的话,getline会更好地工作。
getline (cin, Choice);
In function void PrintMainMenu()
you are creating a new Character. 在函数void PrintMainMenu()
您正在创建一个新角色。 You need to pass a reference on your Character from main into this function. 您需要将来自main的有关角色的引用传递给此函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.