Learn about binary operators and assignment operators in the C++ language

  • 2020-05-09 18:51:46
  • OfStack

The 2 meta operator
The following table shows a list of overloadable operators.
Redefinable base 2 operator

运算符
名称
, 逗号
!= 不相等
% 取模
%= 取模/赋值
& 按位“与”
&& 逻辑“与”
&= 按位“与”/赋值
* 乘法
*= 乘法/赋值
+ 添加
+= 加法/赋值
减法
�= 减法/赋值
< 小于
<< 左移
<<= 左移/赋值
<= 小于或等于
= 赋值
== 相等
> 大于
>= 大于或等于
>> 右移
>>= 右移/赋值
^ 异或
^= 异或/赋值
| 按位“与或”
|= 按位“与或”/赋值
|| 逻辑“或”

To declare a 2-tuple operator function as a non-static member, you must declare it in the following form:


ret-type operatorop( arg )

Where ret-type is the return type, op is the 1 of the operators listed in the table above, and arg is a parameter of any type.
To declare a 2-tuple operator function as a global function, you must declare it in the following form:


ret-type operatorop( arg1, arg2 )

Where ret-type and op are member operator functions, and arg1 and arg2 are parameters. At least one parameter must be of class type.
Pay attention to
There is no restriction on the return type of the 2-bit operator; However, most user-defined 2-tuple operators will return a class type or a reference to a class type.

Assignment operator
Strictly speaking, the assignment operator (=) is a 2-tuple operator. It is declared the same as any other 2-bit operator, with the following exceptions:
It must be a non-static member function. No operator= can be declared as a non-member function.
It does not inherit from a derived class.
The default operator= function can be generated by the compiler of a class type (if the function does not exist). (for more information about the default operator= function, see member assignment and initialization.)
The following example shows how to declare an assignment operator:


// assignment.cpp
class Point
{
public:
 Point &operator=( Point & ); // Right side is the argument.
 int _x, _y;
};

// Define assignment operator.
Point &Point::operator=( Point &ptRHS )
{
 _x = ptRHS._x;
 _y = ptRHS._y;

 return *this; // Assignment operator returns left side.
}

int main()
{
}

Note that the parameter provided is the right-hand side of the expression. This operator returns an object to preserve the behavior of the assignment operator, which returns the value on the left after completion of the assignment. This allows you to write statements like the following:


pt1 = pt2 = pt3;


Related articles: