更正:
我编辑了两行:
1)“ class 圈:公共形状”到“ class 圈子:公共虚拟形状”
2)“ class 广场:公共形状”到“ class 广场:公共虚拟形状”
是的,我试图为 shapes 类只有一个 Shape 类的实例,而在 Circle class和 Square 类中定义方法 draw 则不同
我试图做一个简单的继承程序,但它给了我以下错误:
*错误C2250:'shapes':'void shape::draw(void)'的模糊继承
- IntelliSense:虚拟函数"shape::draw"的覆盖是不明确的
-
此代码类似于钻石问题的解决方案 . 我不明白为什么我看到这个错误 .
这是代码:
#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 回答
(从评论转到答案)
您似乎打算从
shape
虚拟继承,然后在shapes
中提供您自己的draw
函数几乎像这样继承:
然后在
shapes
:Live Demo
Edit
在您的情况下使用虚拟继承本身并不是必需的,因为您的基础是抽象的(只有纯虚方法) . 但是,如果您的用例是基类实现方法,那么您肯定希望使用虚拟继承 . (谢谢@vsoftco)
这是因为虚拟继承保证只有一个基类实例将被继承到
shapes
,而在C中默认情况下在每个派生类中获取它自己的基类实例,因此shapes
实际上将继承shape
的两个实例,一个通过circle
和一到square
. 此时,从shapes
对象调用任何基类函数变得不明确,因为编译器无法确定您要从哪个实例调用它 .