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

单一继承多次

代码:

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

实践很有意思!

posted @ 2016-03-04 22:29  literalkernel  阅读(746)  评论(0编辑  收藏  举报