定义运算符 + , = 和 +=
我曾经在一篇 C++ 笔记中读到过这样的一句话:
在 C++ 中,定义运算符 + 和 = 并没有赋予 += 正确的含义。此语言设计错误已在 C# 中修复
我想知道这句话到底想说什么?这与操作员过载有关吗?
I once read the following statement from a C++ notes,
In C++, defining operator + and = does not give the right meaning to +=. This language-design bug is fixed in C#
I would like to know what exactly does this statement want to say? Is that related to operator overload?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我更喜欢C++运算符重载机制。在我看来,这绝对不是一个设计错误。
+
、=
和+=
是三个不同的运算符。如果你想使用+=
,你需要重载+=
。重载+
和=
不会使+=
工作。我想补充一点,就 C++ 而言,在
E1 += E2
中,E1
仅被评估一次。我不知道C#中的具体规则。I prefer C++ operator overloading mechanism. It definitely not a design bug according to me.
+
,=
and+=
are three different operators. If you want to use+=
you need to overload+=
. Overloading+
and=
won't make+=
work.I would like to add that in
E1 += E2
E1
gets evaluated only once as far as C++ is concerned. I don't know the exact rules in C#.它表示,在 C# 中,如果重载了运算符 +,C# 会自动将运算符 += 模拟为 + 和 = 的组合(
a=a+b
等于a+=b
>)。在 C++ 中它没有实现,但这不是一个错误。在 C++ 中,+ 和 = 不会为您提供 +=,因为大多数情况下 += 比 + 运行得更快,因为不需要再创建一个对象。这就是为什么大多数运算符 + 都是使用 += 运算符编写的。考虑以下代码:
It says, that in C# if you have overloaded operator + C# automatically will emulate operator += as combination of + and = (
a=a+b
is equal toa+=b
). In C++ it's not implemented, but it's not a bug. In C++ + and = doesn't give you += because mostly += works faster than +, because there is no need to create one more object.That's why mostly operator + is writen using += operator. Consider fallowing code:
这意味着在 C++ 中,如果您为您的类定义了自己的运算符
+
和运算符=
,但这并不意味着您的类将自动支持+=
运算符。如果您希望+=
运算符适用于您的类,则必须显式地单独定义+=
。在 C# 中,如果我理解正确的话,为您的类定义运算符
+
和=
也意味着您将能够使用运算符+= 与你的班级。
+=
将通过运算符+
和运算符=
的组合来“模拟”。例如,表达式a += b
将被解释为a = a + b
。在 C++ 中则不然。如果您没有显式定义
+=
,a += b
将导致编译器错误,即使您有+
和>=
已定义。It means that in C++ if you defined your own operator
+
and operator=
for your class, that still does not mean that your class will automatically support the+=
operator. If you want the+=
operator to work for your class, you have to define the+=
explicitly and separately.In C#, if I understood it correctly, defining operators
+
and=
for your class will also mean that you'll be able to use operator+=
with your class. The+=
will be "emulated" through combination of operator+
and operator=
. E.g. expressiona += b
will be interpreted asa = a + b
.It doesn't work that way in C++. If you don't define the
+=
explicitly,a += b
will result in compiler error, even if you have+
and=
defined.C# 不允许运算符重载=,因为它不允许直接的指针管理。它的行为是根据它是引用类型还是值类型而固定的。出于同样的原因,您不能重载 += 。它的含义始终是进行求和和赋值。因此,您只能决定 + 对您的数据结构的含义。
C# does not allow operator overloading = since it does not allow direct pointer management. Its behavior is fixed based on whether it is reference or value type. For the same reason you cannot overload += . It's meaning will always be doing the sum and assignment. You can only therefore decide what the meaning for + is to your datastructure.