我有两个类,其中一个有一个私有(private)变量。还有一个成员函数可以更改此变量,还有一个get函数可以读取它。这样的类可能看起来像这样。
class Toggler {
public:
void change()
{
randomBool = !randomBool;
}
bool getBool()
{
return randomBool;
private:
bool randomBool = false;
};
现在,另一个函数可以尝试使用getBool()函数读取此 bool(boolean) 值的状态。可能看起来像这样:
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()给我正确的值,但是,如果我通过单独的类中的另一个函数运行相同的函数,则不会得到相同的结果。
最佳答案
Toggler toggler;
中的函数内的class Reader
变量与Toggler toggler;
中的main
变量无关。它们具有相同的名称,但是没有连接。
您正在更改一个,然后打印另一个。当然,您看不到任何效果。