c++ - c++中的重写函数

标签 c++ overriding member-hiding

#include <iostream>

using namespace std;

class Base {
public:
virtual void some_func(int f1)
{
cout <<"Base is called: value is : " << f1 <<endl;
}
};

class Derived : public Base {
public:
virtual void some_func(float f1)
{
cout <<"Derived is called : value is : " << f1 <<endl;
}
};


int main()
{
int g =12;
float f1 = 23.5F;

Base *b2 = new Derived();
b2->some_func(g);
b2->some_func(f1);
return 0;

}

输出是:

Base is called: value is : 12
Base is called: value is : 23

为什么第二次调用 b2->some_func(f1) 调用 Base 类的函数,即使在 Derived 中有一个以 float 作为参数的版本可用类?

最佳答案

  1. 它实际上并没有被覆盖,因为它的参数没有相同的类型。
  2. 因为它没有被覆盖,你指向 Base 的指针只知道 int 方法,所以它执行收缩转换(应该有警告)并调用 Base::some_func(int).

关于c++ - c++中的重写函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17488622/

相关文章:

c# - Windows 64 位地址空间

java类A扩展了类B,并覆盖了方法

c++ - 隐藏重载的虚函数

c++ - 左移计数 >= 类型宽度 - 单独添加 UL 或强制转换不能解决问题

c++ - MFC CToolBar 帮助/链接?

c++ - 无法将参数 1 从派生指针转换为基类指针引用

java - 如何使用 Scala 覆盖 java.awt.Component 中的字体?

python - 是否可以全局覆盖 print() ?

java - 父类和实现的接口(interface)具有相同名称的字段,并且仅在一个类差异内

Java 名称隐藏 : The Hard Way