我试图让这个程序获取用户输入并将其放入公共函数并将其分配给privateVariable,然后我希望它返回privateVariable转换为main()并将其输出到屏幕,但它显示的是未定义int(-858993460)的值。我在这里有什么逻辑问题?C++类没有返回我的私有变量的正确值
#include <iostream>
#include <string>
using namespace std;
class MyClass
{
private:
int privateVariable;
public:
int userVariable;
void setVariable(int userVariable)
{
privateVariable = userVariable;
}
int getVariable()
{
return privateVariable;
}
};
int main()
{
int userVariable;
cin >> userVariable;
MyClass object1;
MyClass object2;
object1.setVariable(userVariable);
object2.getVariable();
cout << object2.getVariable();
system("PAUSE");
return 0;
}
为什么你要为'object1'设置变量并尝试从'object2'中取回它?要么你错过了'静态'变量的概念,或者你做了一个类型,我猜想。 – arne