C:当非重写调用重写方法时会发生什么?
作者:互联网
被调用的重写方法的版本取决于
如果你关心调用函数“通过”基类或“通过”派生类.但是,我发现如果我调用一个非重写的方法,并且重写的方法调用一些被覆盖的函数,那么仍然会调用基类版本,即使我通过指向派生类的指针访问实例.有人能解释为什么会这样吗?
码:
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?
尽管通过指向派生类的指针调用方法,但是您的方法不是虚拟的,因此使用静态调度,因此Base :: display()直接调用Base :: foo(),即使它在子类中被重写.要实现所需的行为,必须使用动态分派,即将方法标记为虚拟.
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()
标签:method-overriding,c,function-overriding,member-hiding 来源: https://codeday.me/bug/20190829/1762461.html