开发者

C++, ambiguous inheritance error in vs 2010

开发者 https://www.devze.com 2023-03-24 21:11 出处:网络
I have some troubles with the application of polymorphism in this example. This question is similar to my last question

I have some troubles with the application of polymorphism in this example. This question is similar to my last question

C++, virtual inheritance, strange abstract class + clone problem

There are 3 abstract classes:

class A
{
public:
    virtual A  * copy () const = 0;
    virtual ~A() = 0;
};

A::~A(){}

class B
{
public:
    virtual B  * copy () const = 0;
    virtual ~B() = 0;
};

B::~B(){}

class C: virtual public A , public B 
{
public:
    virtual C  * copy () const = 0;
    virtual ~C() = 0;
};

C::~C(){}

and two inherited classes using the virtual inheritance

class D: virtual public A
{
public:
    virtual D  * copy () const {return new D  (*this);}
    virtual ~D() {}
};

class E: virtual public D , public C
{
public:
    virtual E * copy () const {return new E (*this);}
    virtual ~E() {}
}; //Error C2250: 'E' : ambiguous inheritance of 'D *A::copy(void) const

The above mentioned error occurs only using MSVS 2010 compiler, g++ compiles this code OK.

Class diagram (simplified)

.......... A .... B.....
........../.\..../......
........./...\../.......
......../.....\/........
.......D...... C........
........\...../.........
.........\.../..........
..........\./...........
...........E............

Last discussion we close with the result: remove the declaration of the copy() method from class C.

class C: virtual public A , public B 
{
public:
    //virtual C  * copy () const = 0; //remove declaration
    virtual ~C() = 0;
};

C::~C(){}

My sample code using polymorphism needs to create vector of pointers to C. After removing some element I want to create its copy... I NEED a declaration of copy() in class C, so removal of the declaration is insufficient and it does not s开发者_开发知识库olve the problem.

int main(int argc, char* argv[])
{
std::vector <C*> items;
items.push_back(new E());
items.push_back(new E());
items[0]->copy();
return 0;
}

Could you help me, please how to correct the code to be translatable using VS 2010?


This is a known bug in Visual C++:

Visual C++ incorrectly reports ambiguity when covariance is used with virtual inheritance

You either need to eliminate the covariance or the virtual inheritance. Unfortunately, you can't have both.

0

精彩评论

暂无评论...
验证码 换一张
取 消