#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作为参数的版本?
答案 0 :(得分:4)
Base
的指针只知道int
方法,因此它会执行缩小转换(应该有警告)并调用Base::some_func(int)
。答案 1 :(得分:2)
你把重载与重写相混淆, 对于重写,函数的签名必须保持不变。 请再次查看c ++文档..希望这有用