gpt4 book ai didi

c++ - 运算符继承

转载 作者:行者123 更新时间:2023-12-01 14:15:02 24 4
gpt4 key购买 nike

我有以下代码:

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;编译器给我一个错误:

no match for 'operator=' (operand types are 'Square' and 'Rectangle')

为什么这条线不起作用?

最佳答案

如果您不提供赋值运算符,则编译器 will declare一个给你。此处,编译器生成 Square::operator=(const Square&)Rectangle 中的赋值运算符被此运算符隐藏。您可以使用 using declarationRectangle::operator= 带入范围内:

class Square : public Rectangle
{
public:
using Rectangle::operator=;

// ...
};

现在代码可以编译,但是有缺陷。正如 Konrad Rudolph、Jarod42 和 molbdnilo 在评论中指出的那样,从 Rectangle 派生 Square 在逻辑上是错误的,因为它 violates Liskov's substitution principle .您现在可以将 Rectangle 分配给 Square,这样的分配没有任何意义。

关于c++ - 运算符继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61383936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com