c++ 多态

本文通过一个C++程序实例介绍了多态与继承的概念。示例中定义了Grandpa、Parent和Son三个类,并演示了如何使用虚函数实现多态特性。文章通过具体的输出结果解释了不同情况下成员函数调用的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值