单一继承多次

代码:

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

实践很有意思!

相关文章:

  • 2021-10-25
  • 2021-07-07
  • 2021-12-01
  • 2020-06-08
  • 2022-01-10
  • 2022-02-15
  • 2021-04-23
猜你喜欢
  • 2021-09-15
  • 2022-12-23
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
相关资源
相似解决方案