int main(int argc, char* argv[])
{
Child child();
std::cout << child.GetFoo();
}
输出为
0
为什么我对这种交互的最初理解是不正确的,我将如何达到我的预期行为,在派生类的实例上呼叫getter将返回派生类的静态成员?
由于成员变量不是虚拟的。在
Parent::foo
的背景下,您已经遮蔽了Child
Parent
的成员。如果您真的需要这种行为,则需要以某种方式支付间接费用。例如:
class Parent
{
protected:
virtual int foo() {
return 0;
}
public:
int GetFoo()
{
return foo();
}
};
class Child : Parent
{
protected:
virtual int foo() override {
return 1;
}
};