我有以下代码:
class Rectangle
{
protected:
int a, b;
public:
Rectangle(int a, int b) : a(a), b(b) {}
int area() { return a*b; }
Rectangle operator+(const Rectangle & other)
{
Rectangle temp(0, 0);
temp.a = a + other.a;
temp.b = b + other.b;
return temp;
}
void operator=(const Rectangle & other)
{
a = other.a;
b = other.b;
}
};
class Square : public Rectangle
{
public:
Square(int a) : Rectangle(a, a) {}
};
int main()
{
Square s1(3);
Square s2(1);
cout << (s1 + s2).area();
s1 = s1 + s2;
}
cout << (s1 + s2).area();
还可以,但在s1 = s1 + s2;
编译器给我一个错误:
"operator="不匹配(操作数类型为"Square"one_answers"Rectangle"(
为什么这一行不起作用?
如果不提供赋值运算符,编译器将为您声明一个。这里,编译器生成Square::operator=(const Square&)
。Rectangle
中的赋值运算符被此运算符隐藏。您可以使用using
声明将Rectangle::operator=
带入范围:
class Square : public Rectangle
{
public:
using Rectangle::operator=;
// ...
};
现在代码可以编译了,但是有缺陷。正如Konrad Rudolph、Jarod42和molbdnilo在评论中所指出的,从Rectangle
导出Square
在逻辑上是错误的,因为它违反了Liskov的替代原则。现在可以将Rectangle
分配给Square
,但这样的分配没有意义。