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

  • 2020-05-07 20:13:58
  • OfStack

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

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

To declare a 2-bit 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 above table, and arg is an argument of any type.
To declare a 2-bit 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, while 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 2-bit operators; However, most user-defined 2-meta operators return a class type or a reference to a class type.

assignment operator
Strictly speaking, the assignment operator (=) is a 2-bit operator. Its declaration is the same as any other 2-byte operator, with the following exceptions:
It must be a non-static member function. No operator= can be declared as a non-member function.
It is not inherited by a derived class.
The default operator= function can be generated by the compiler of the class type (if the function does not exist). (for more information about the default operator= function, see member assignment and initialization.)
The following example illustrates 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 supplied parameter is the right 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 the assignment. This allows you to write statements similar to the following:


pt1 = pt2 = pt3;


Related articles: