为什么C#不容许运算符重载?不容许、运算符

2023-09-03 04:40:55 作者:幸福ヾ漸行漸遠

为什么C#不允许操作符重载,而C ++呢?

我得到这个错误,尝试过载的时候。

重载的二元运算符预期

我的样品code样子,

 公共静态MyClass的操作符+ =(MyClass的OBJ1,MyClass的OBJ2)
        {
           ...
        }
 

解决方案

您可以在C#中重载运算符:

MSDN教程 C 之操作符重载探究 四 下标运算符重载

在你决定使用操作符重载,请阅读最起码,如下:

批评运算符重载的

编辑回应运算的编辑:

+ = 是一个非重载的运算符。然而,它解析为 + + 是重载的。有一个看看这里为其运营商就可以,不能超载。

运算符可以重载:

+ ! - + -

+ - * / &安培; | ^ << > >

== = <!> < = > = (比较运算符可以重载,但看到音符链接)

why c# not allowed operator overloading while C++ do?

I got this error, when trying to overload.

Overloadable binary operator expected

My sample code looks like,

public static MyClass operator +=(MyClass obj1, MyClass obj2)
        {
           ...
        }

解决方案

You can overload operators in C#:

MSDN Tutorial

Before you decide to use operator overloading, please read at the very least, the following:

Criticisms of Operator Overloading

EDIT in response to op's edit:

The += is a non-overloadable operator. However, it resolves to +, and + is overloadable. Have a look here for which operators you can and can not overload.

Operators that can be overloaded:

+, -, !, ~, ++, --, true, false

+, -, *, /, %, &, |, ^, <<, >>

==, !=, <, >, <=, >= (The comparison operators can be overloaded but see note in link)