为什么继承失败(使用超类的方法)
Why does this inheritance fail (method of super class is used) 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时不应该被调用吗?如果这是应该的,我如何才能获得我想要的行为?
您需要将get_number
标记为virtual
才能正常工作。
在c++中,一分钱一分货。由于多态性增加了开销(内存和运行时),因此指向虚拟方法表的指针&动态调度),您必须明确希望在运行时解析哪些函数调用。由于get_number
不是virtual
,来自tell_me_the_number
的调用将在编译时解析,并将调用基类版本。
相关文章:
- 重写另一个方法 [C++] 使用的超类回调函数
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- 使用派生类C++方法的超类
- 为什么编译器找不到超类的方法?
- 对超类方法的未定义引用
- 将 void* 强制转换为多个继承类的超类不会调用正确的方法
- 子类是否也在 c++ 中继承私有数据成员?但通过超类的公共方法访问
- cpp 从需要超类对象的函数访问子类对象方法
- 具有与专用列表一起使用的参数列表的超类方法<superclass>
- 在C++中,继承超类的正确方法是什么,以便它们的子类在超级类和子类中没有重复的属性?
- 超类::方法或这个>方法的区别
- 强制接收实现接口的超类指针作为方法的参数
- C++ 在超类构造函数中运行依赖于子类覆盖的大量变量的代码的正确方法是什么?
- C++在作为超类传递后使用overriden方法
- C++调用模板化超类的继承方法
- 如何在超类方法的参数中使用子类
- 关于在强制转换为子类的超类时调用其重写方法
- 将 std::unique_ptr 转换为 std::unique_ptr 转换为超类的正确方法是什么?
- 如何在qt c++中的子类中重载超类方法
- c++继承.对象调用超类方法而不是自己的方法