繁体   English   中英

C ++中的重写函数

[英]overriding functions in c++

#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 ++文档。.希望这对您有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM