【发布时间】:2017-06-03 15:13:30
【问题描述】:
我有两个类,其中一个有一个私有变量。还有一个成员函数来更改这个变量和一个 get 函数来读取它。这样的类可能看起来像这样。
class Toggler {
public:
void change()
{
randomBool = !randomBool;
}
bool getBool()
{
return randomBool;
private:
bool randomBool = false;
};
另一个函数现在可以尝试使用 getBool() 函数读取此布尔值的状态。可能看起来像这样:
class Reader {
public:
void printer()
{
Toggler toggler;
cout << toggler.getBool() << endl;
}
};
现在,如果我最终从我的主类中运行所有这些函数,就像这样:
Reader reader;
Toggler toggler;
cout << toggler.getBool() << endl;
reader.printer();
toggler.change();
cout << toggler.getBool() << endl;
reader.printer();
这将输出 0,0,1,0。 这里的问题是直接函数 toggler.getBool() 给了我正确的值,但是如果我通过单独类中的另一个函数运行相同的函数,我不会得到相同的结果。
【问题讨论】:
-
那么,通过单独的类运行会得到什么结果?您确实意识到每次调用
printer()时都会重新创建class Reader中的Toggler,并且完全独立于主类中的Toggler toggler:?我不能真正理解你的问题是什么......
标签: c++ class variables private member