简体   繁体   English

关于多重继承和虚拟继承

[英]about Multiple inheritance and virtual inheritance

I don't quite understand Multiple inheritance and virtual inheritance.我不太了解多重继承和虚拟继承。 plz help me.请帮助我。 Here is my little test:这是我的小测试:

class Test1
{};

class Test21 : public Test1
{};

class Test22 : public Test1
{};

class Test3 : public Test21, public Test22
{};

int main()
{
    Test1  * t1 = new Test3();
    delete t1;

    system("pause>NUL");
    return 0;
}

I got an error: Error 1 error C2594: 'initializing' : ambiguous conversions from 'Test3 *' to 'Test1 *' .我收到一个错误: Error 1 error C2594: 'initializing' : ambiguous conversions from 'Test3 *' to 'Test1 *'
WHY?为什么?

Then I tried like this:然后我尝试这样:

class Test1
    {};

    class Test21 : virtual public Test1
    {};

    class Test22 : virtual public Test1
    {};

    class Test3 : public Test21, public Test22
    {};

    int main()
    {
        Test1  * t1 = new Test3();
        delete t1;

        system("pause>NUL");
        return 0;
    }

Now I got another error: Debug Assertion Failed!现在我收到另一个错误: Debug Assertion Failed!

Can someone explain me about Multiple inheritance and virtual inheritance?有人可以解释一下多重继承和虚拟继承吗?

Your first piece of code has the exact problem that virtual inheritance solves: you have a diamond in your inheritance hierarchy.您的第一段代码具有虚拟继承解决的确切问题:您的继承层次结构中有一个菱形。 Test21 and Test22 both inherit from Test1 , so when you inherit from both of them, you actually get two versions of Test1 in your hierarchy, so it is ambiguous as to which one you wish to use. Test21Test22都继承自Test1 ,因此当您从它们两个继承时,您实际上在您的层次结构中获得了Test1两个版本,因此您希望使用哪个版本是不明确的。

The solution, is in your second sample: virtually inherit from Test1 so that you just get a single version.解决方案在您的第二个示例中:从Test1虚拟继承,以便您只获得一个版本。

However, your code has undefined behaviour.但是,您的代码具有未定义的行为。

Test1  * t1 = new Test3();
delete t1;

You delete a derived instance through a pointer to a base class without a virtual destructor.您可以通过指向没有虚拟析构函数的基类的指针删除派生实例。 This means that the Test3 object is not correctly destroyed.这意味着Test3对象没有被正确销毁。

You should add virtual destructors to your classes:你应该在你的类中添加虚拟析构函数:

virtual ~Test1() = default; //c++11
virtual ~Test1() {}; //prior version

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM