码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-03-05 00:01:49      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:

单一继承多次

代码:

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

实践很有意思!

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

标签:

原文地址:http://www.cnblogs.com/sinx/p/5243682.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!