简单的虚拟继承&纯虚方法程序

时间:2015-04-04 16:22:23

标签: c++


更正:

我编辑了两行:

1)“班级圈:公共形状”到“班级圈子:公共虚拟形状​​”

2)“class square:public shape”to“class square:public virtual shape”

是的,我正在尝试为 形状 类只有一个 Shape 类的实例,在 Circle 类和 Square < 中以不同方式定义方法 draw / strong> class


我正在尝试做一个简单的继承程序,但它给了我以下错误:

*错误C2250:'形状':'void shape :: draw(void)'的模糊继承 * IntelliSense:虚拟函数“shape :: draw”的覆盖是不明确的

- &gt;此代码类似于钻石问题的解决方案。我不明白为什么我会看到这个错误。

以下是代码:

    #include<iostream>
    using namespace std;
    class shape
    {
    public:
        shape()
        {
            cout << "shape created" << endl;
        }
        virtual void  draw()=0;


    };

    class circle : public virtual shape
    {
    public:
        circle()
        {
            cout << "circle created" << endl;
        }
        virtual void  draw()
        {
            cout << "this is a circle" << endl;
        }
    };

    class square : public virtual  shape
    {
    public:
        square()
        {
            cout << "square created" << endl;
        }
        virtual void  draw()
        {
            cout << "this is a square" << endl;
        }
    };

    class shapes : public  circle, public  square
    {
    public:
        shapes()
        {
            cout << "shapes created" << endl;
        }
    };

    void main()
    {
        shapes e;
        cout << "-------------" << endl;
        system("pause");
    }

1 个答案:

答案 0 :(得分:1)

(从评论转到答案)

您似乎打算从shape虚拟继承,然后在draw

中提供您自己的shapes功能

几乎像这样继承:

class circle : public virtual shape //and same for class square

然后在shapes

class shapes : public  circle, public  square
{
public:
    shapes()
    {
        cout << "shapes created" << endl;
    }

    virtual void draw() //'virtual' is optional here
    {
        circle::draw();
        square::draw();
    }
};

Live Demo

修改

在您的情况下使用虚拟继承本身并不是必需的,因为您的基础是抽象的(只有纯虚方法)。但是,如果您的用例是基类实现方法,那么您肯定希望使用虚拟继承。 (谢谢@vsoftco)

这是因为虚拟继承保证只有一个基类实例将被继承到shapes,而在C ++中,默认情况下每个派生类都有自己的基类实例,所以shapes会实际上继承了shape的两个实例,一个到circle,一个到square。此时,从shapes对象调用任何基类函数变得不明确,因为编译器无法确定您要从哪个实例调用它。