#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();
}
c++ 多态
最新推荐文章于 2025-04-03 18:53:51 发布
本文通过一个C++程序实例介绍了多态与继承的概念。示例中定义了Grandpa、Parent和Son三个类,并演示了如何使用虚函数实现多态特性。文章通过具体的输出结果解释了不同情况下成员函数调用的行为。
1632

被折叠的 条评论
为什么被折叠?



