访问 parent class 个变量
Accessing parent class variables
我觉得这应该很容易,但我仍然无法正常工作。
我不知道这里的最佳做法是什么。我首先尝试通过引用存储传递给 child class 的变量,然后在 child class 中调用它。除了,当 parent class 中的变量发生变化时,child 没有看到变化。
child:
class Child
{
public:
Child(bool &EndLoop);
~Child();
private:
bool EndLoopRef;
};
Child::Child (bool &EndLoop) : EndLoopRef(EndLoop)
{
}
Child::PrimaryFunction()
{
while (!Child::EndLoopRef)
{
// Main app function is in here
}
// EndLoop is true, we can now leave this method
}
parent:
class Parent
{
public:
Parent();
~Parent();
private:
bool EndLoop;
};
Parent::Parent()
{
Child childclass(EndLoop);
childclass.PrimaryFunction();
// EndLoop was changed and the loop is now overe
}
总而言之,parent class 通过引用传递 EndLoop
。 child class 存储此引用并等待 EndLoopRef 的真值退出循环。不用说,它并没有结束循环。
仅供参考,EndLoop 值由 parent class.
中的系统调用更改
将您的 class 成员命名为 bool EndLoopRef;
并不能使其成为参考。这仍然只是一个 bool
值,构造函数的成员初始化将在构造时加载 EndLoop
的值。
您已经展示了如何使用 &
定义引用。
不应通过引用传递私有变量。与 private 交互的最佳方式是在具有成员变量的 class 中使用 get() 和 set() 方法。在这种情况下,您的父值可以提供一个 getEndLoop() 函数,该函数将 return 布尔值。
Child::PrimaryFunction()
{
while (!Parent.getEndLoop())
{
// Main app function is in here
}
// EndLoop is true, we can now leave this method
}
您尚未将其定义为引用。
你要说:
bool &EndLoopRef;
我觉得这应该很容易,但我仍然无法正常工作。
我不知道这里的最佳做法是什么。我首先尝试通过引用存储传递给 child class 的变量,然后在 child class 中调用它。除了,当 parent class 中的变量发生变化时,child 没有看到变化。
child:
class Child
{
public:
Child(bool &EndLoop);
~Child();
private:
bool EndLoopRef;
};
Child::Child (bool &EndLoop) : EndLoopRef(EndLoop)
{
}
Child::PrimaryFunction()
{
while (!Child::EndLoopRef)
{
// Main app function is in here
}
// EndLoop is true, we can now leave this method
}
parent:
class Parent
{
public:
Parent();
~Parent();
private:
bool EndLoop;
};
Parent::Parent()
{
Child childclass(EndLoop);
childclass.PrimaryFunction();
// EndLoop was changed and the loop is now overe
}
总而言之,parent class 通过引用传递 EndLoop
。 child class 存储此引用并等待 EndLoopRef 的真值退出循环。不用说,它并没有结束循环。
仅供参考,EndLoop 值由 parent class.
中的系统调用更改将您的 class 成员命名为 bool EndLoopRef;
并不能使其成为参考。这仍然只是一个 bool
值,构造函数的成员初始化将在构造时加载 EndLoop
的值。
您已经展示了如何使用 &
定义引用。
不应通过引用传递私有变量。与 private 交互的最佳方式是在具有成员变量的 class 中使用 get() 和 set() 方法。在这种情况下,您的父值可以提供一个 getEndLoop() 函数,该函数将 return 布尔值。
Child::PrimaryFunction()
{
while (!Parent.getEndLoop())
{
// Main app function is in here
}
// EndLoop is true, we can now leave this method
}
您尚未将其定义为引用。 你要说:
bool &EndLoopRef;