#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
12-15两义性在重载时的一些问题
---------------------------------*/
class a
{
public:
void hello()
{cout<<"基类a的hello函数"<<endl;}
void hello(int i) //重载hello
{
cout<<"a.hello(i):"<<i<<endl;
cout<<"基类a的带一个参数的hello函数"<<endl;
}
};
class b:public a
{
public:
void hello() //父类的hello被子类改造 无const修饰符->屏蔽隐藏父类的hello函数;在虚函数里,将破坏多态性
// void hello()const //父类的hello被子类改造 有const修饰符->覆盖替换父类的hello函数;在虚函数里,将支持多态性
{cout<<"子类b的hello函数"<<endl;}
void hello(int i) //子类b中重载hello
{
cout<<"b.hello(i):"<<i<<endl;
cout<<"子类b的带一个参数的hello函数"<<endl;
}
};
int main()
{
b b;
b.hello(); //由于继承并改造了hello(),则调用的是子类的hello()
b.hello(1); //如果子类b中没有重载hello,会编译出错,因为父类的hello被子类改造了
cout<<"-----------------------"<<endl;
a a;
a.hello();
a.hello(2);
return 0;
}
运行结果:
子类b的hello函数
b.hello(i):1
子类b的带一个参数的hello函数
-----------------------
基类a的hello函数
a.hello(i):2
基类a的带一个参数的hello函数
Press any key to continue