考虑这个简单的程序:
class Shape
{
public:
virtual double getArea() = 0;
};
class Rectangle : public Shape
{
int width;
int height;
public:
Rectangle( int w , int h ) :width(w) , height(h) {}
double getArea() const
{
return width * height;
}
};
int main() {
Rectangle* r = new Rectangle(4,2);
}
尝试编译这个问题给了我:
'Rectangle' : cannot instantiate abstract class
为什么在 C++ 中不允许这样做,而协变返回类型是允许的?当然我可以通过以下方式修复程序Rectangle::getArea
是一个非常量函数但我很好奇为什么语言设计者做出了不同的决定。
EDIT
很多人在他们的答案中提到了签名的不同之处。但也是如此
class Shape
{
public:
virtual BaseArea* getArea() = 0;
};
class Rectangle : public Shape
{
public:
virtual RectangleArea* getArea();
};
但是 C++ 不遗余力地允许这种情况发生,而 C# 却不允许这样做。
C++ 支持协变返回类型,因为如果我期望一个接口返回一个BaseArea*
并且一个实现返回一个RectangleArea*
,只要 RectangleArea 派生自 BaseArea 就可以了,因为我的合同得到了满足。
同样,提供非变异函数的实现不是满足仅要求变异函数的接口吗?
在这种情况下会发生什么:
struct base
{
virtual void foo(); // May implement copy-on write
virtual void foo() const;
};
struct derived : base
{
// Only specialize the const version, the non const
// default suits me well. How would I specify that I don't
// want the non-const version to be overriden ?
void foo() const;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)