被调用的覆盖方法的版本取决于 如果您关心“通过”基类或“通过”派生类调用函数。但是,我发现如果我调用一个非重写方法,并且重写方法调用一些被重写的函数,那么基类版本仍然被调用,即使我通过指针访问实例到派生类。有人可以解释为什么会这样吗?
代码:
class Base {
public:
void display() {
foo();
}
void foo() {
cout << "Base.foo()" << endl;
}
};
class Derived : public Base {
public:
void foo() {
cout << "Derived.foo()" << endl;
}
};
int main() {
Derived* derived = new Derived();
derived->display();
while (true) {}
}
最佳答案
the base class version is still called, even though I am accessing the instance through pointer to the derived class. Could someone explain why this happens?
虽然您通过指向派生类的指针调用方法,但您的方法不是虚拟的,因此使用静态分派(dispatch),所以 Base::display()
调用 Base::foo()
直接,即使它在子类中被覆盖。要实现您想要的行为,您必须使用动态调度,即将您的方法标记为 virtual
。
class Base {
public:
void display() {
foo();
bar();
}
void foo() {
cout << "Base.foo()" << endl;
}
virtual void bar() {
cout << "Base.bar()" << endl;
}
};
class Derived : public Base {
public:
void foo() {
cout << "Derived.foo()" << endl;
}
virtual void bar() {
cout << "Derived.bar()" << endl;
}
};
int main() {
Derived* derived = new Derived();
derived->display();
}
输出:
Base.foo()
Derived.bar()
关于C++ : What is happening when a non-overridden calls a overridden method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334313/