【发布时间】:2013-07-03 12:59:40
【问题描述】:
#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 作为参数的版本?
【问题讨论】:
-
有一个新的 C++11 关键字
override。把它放在Derived中的方法签名some_func的末尾,错误信息会有所帮助。 -
永远不要忘记删除堆指针。
标签: c++ overriding member-hiding