您的位置:首页 > 编程语言 > C语言/C++

c++ 多态

2015-07-06 11:09 501 查看
#include <iostream>
#include <string>
using namespace std;
class Grandpa
{
protected:
int age_;
public:
Grandpa(int age = 100)
{
age_ = age;
cout << "对象Grandpa构造完成!" << endl;
}
int GetAge()
{
return doGetAge();
}
virtual int doGetAge()
{
return age_;
}
};
class Parent : public Grandpa
{
protected:
int age_;
public:
Parent(int age = 70)
{
age_ = age;
cout << "对象Parent构造完成!" << endl;
}
int doGetAge()
{
return age_;
}
};
class Son : public Parent
{
protected:
int age_;
public:
Son(int age = 40)
{
age_ = age;
cout << "对象Son构造完成!" << endl;
}
};
void main()
{
Son son(10);//依次调用构造函数,初始化Grandpa的age_=100,Parent的age_=70,Son的age_=40

//以下调用结果一样,原因如下
//1.调用的主体是子类Son
//2.调用的函数实际是虚函数doGetAge()----多态
cout << son.GetAge() << endl;
cout << son.Grandpa::GetAge() << endl;//
cout << son.Parent::GetAge() << endl;
cout << son.Son::GetAge() << endl;
//以下调用结果不一样,原因如下
//doGetAge()调用时直接指定了类名
cout << son.doGetAge() << endl;//70,继承自Parent
cout << son.Grandpa::doGetAge() << endl;//100,Grandpa有实现doGetAge()方法
cout << son.Parent::doGetAge() << endl;//70
cout << son.Son::doGetAge() << endl;//70,继承自Parent
cin.get();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: