我有以下类(class)
#include <iostream>
using namespace std;
class A {
public:
int get_number() {return 1;}
void tell_me_the_number() {
cout << "the number is " << get_number() <<"\n";
}
};
class B: public A {
public:
int get_number() {return 2;}
};
int main() {
A a;
B b;
a.tell_me_the_number();
b.tell_me_the_number();
}
我希望这会输出给我:
the number is 1
the number is 2
但实际上我得到的是第一行的两倍。
B类的get_number()方法不是应该在是B类的时候调用吗?如果这是应该的,我怎样才能获得我想要的行为?
最佳答案
需要标记get_number
作为virtual
为了这个工作。
在 C++ 中,一分钱一分货。由于多态性增加了开销(内存和运行时 - 指向虚拟方法表和动态调度的指针),您必须明确说明要在运行时解析哪些函数调用。自 get_number
不是 virtual
, 来自 tell_me_the_number
的电话将在编译时解析并调用基类版本。
关于c++ - 为什么这种继承失败(使用父类(super class)的方法)C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16780629/