2013-05-27 21 views
0

我有以下类为什么这种继承失败(父类的方法是使用)C++

#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 

但在现实中,我得到两倍于1号线。

B类的get_number()方法在B类时不应该被调用吗?如果这是应该的,我该如何获得我想要的行为?

回答

6

您需要将get_number标记为virtual才能生效。

在C++中,你得到了你所付出的。由于多态性会增加开销(内存和运行时 - 指向虚拟方法表&动态分派),因此您必须明确指出要在运行时解析哪些函数调用。由于get_number不是virtual,因此tell_me_the_number的调用将在编译时解析并调用基类版本。

相关问题