单一继承多次与多重继承的构造与析构

本文通过具体的 C++ 代码示例介绍了单一继承和多重继承的概念,展示了构造函数和析构函数的调用顺序,并附有清晰的类图说明。

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

单一继承多次

代码:

class great_great_father
{
public:
    great_great_father()
    {
        cout << "function: \tgreat_great_father()" << std::endl;
    }
    ~great_great_father()
    {
        cout << "function: \t~great_great_father()" << std::endl;
    }
};

class great_father : public great_great_father
{
public:
    great_father()
    {
        cout << "function: \tgreat_father()" << std::endl;
    }
    ~great_father()
    {
        cout << "function: \t~great_father()" << std::endl;
    }
};

class father : public great_father
{
public:
    father()
    {
        cout << "function: \tfather()" << std::endl;
    }
    ~father()
    {
        cout << "function: \t~father()" << std::endl;
    }
};

class son : public father
{
public:
    son()
    {
        cout << "function: \tson()" << std::endl;
    }
    ~son()
    {
        cout << "function: \t~son()" << std::endl;
    }
};
int main(int argc, char *argv[])
{
    {
        son s;
    }

    system("pause");
    return 0;
}

son s;语句放在代码块里,使得析构放在主函数结束前。

类图如下

运行结果:

 

多重继承

代码:

class father1
{
public:
    father1()
    {
        cout << "function: \tfather1()" << std::endl;
    }
    ~father1()
    {
        cout << "function: \t~father1()" << std::endl;
    }
};

class father2
{
public:
    father2()
    {
        cout << "function: \tfather2()" << std::endl;
    }
    ~father2()
    {
        cout << "function: \t~father2()" << std::endl;
    }
};

class father3
{
public:
    father3()
    {
        cout << "function: \tfather3()" << std::endl;
    }
    ~father3()
    {
        cout << "function: \t~father3()" << std::endl;
    }
};

class son : public father1, public father2, public father3
{
public:
    son()
    {
        cout << "function: \tson()" << std::endl;
    }
    ~son()
    {
        cout << "function: \t~son()" << std::endl;
    }
};
int main(int argc, char *argv[])
{
    {
        son s;
    }

    system("pause");
    return 0;
}

类图:

运行结果:

编译器:Visual Studio 2015 -> cl.exe

实践很有意思!

转载于:https://www.cnblogs.com/sinx/p/5243682.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值