- Operator overloading
- Syntax
- Remarks
- Redefinable Operators
- Nonredefinable Operators
- Example
- In this section
- Перегрузка операторов
- Синтаксис
- Комментарии
- Переопределяемые операторы
- Непереопределяемые операторы
- Пример
- В этом разделе
- Operator overloading
- Syntax
- Remarks
- Redefinable Operators
- Nonredefinable Operators
- Example
- In this section
- General Rules for Operator Overloading
Operator overloading
The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or «overloads» it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.
Syntax
type operator operator-symbol ( parameter-list )
Remarks
You can redefine the function of most built-in operators globally or on a class-by-class basis. Overloaded operators are implemented as functions.
The name of an overloaded operator is operator x, where x is the operator as it appears in the following table. For example, to overload the addition operator, you define a function called operator+. Similarly, to overload the addition/assignment operator, +=, define a function called operator+=.
Redefinable Operators
Operator | Name | Type |
---|---|---|
, | Comma | Binary |
! | Logical NOT | Unary |
!= | Inequality | Binary |
% | Modulus | Binary |
%= | Modulus assignment | Binary |
& | Bitwise AND | Binary |
& | Address-of | Unary |
&& | Logical AND | Binary |
&= | Bitwise AND assignment | Binary |
( ) | Function call | — |
( ) | Cast Operator | Unary |
* | Multiplication | Binary |
* | Pointer dereference | Unary |
*= | Multiplication assignment | Binary |
+ | Addition | Binary |
+ | Unary Plus | Unary |
++ | Increment 1 | Unary |
+= | Addition assignment | Binary |
— | Subtraction | Binary |
— | Unary negation | Unary |
— | Decrement 1 | Unary |
-= | Subtraction assignment | Binary |
-> | Member selection | Binary |
->* | Pointer-to-member selection | Binary |
/ | Division | Binary |
/= | Division assignment | Binary |
Less than | Binary | |
< | Left shift | Binary |
Left shift assignment | Binary | |
Less than or equal to | Binary | |
= | Assignment | Binary |
== | Equality | Binary |
> | Greater than | Binary |
>= | Greater than or equal to | Binary |
>> | Right shift | Binary |
>>= | Right shift assignment | Binary |
[ ] | Array subscript | — |
^ | Exclusive OR | Binary |
^= | Exclusive OR assignment | Binary |
| | Bitwise inclusive OR | Binary |
|= | Bitwise inclusive OR assignment | Binary |
|| | Logical OR | Binary |
~ | One’s complement | Unary |
delete | Delete | — |
new | New | — |
conversion operators | conversion operators | Unary |
1 Two versions of the unary increment and decrement operators exist: preincrement and postincrement.
See General Rules for Operator Overloading for more information. The constraints on the various categories of overloaded operators are described in the following topics:
The operators shown in the following table cannot be overloaded. The table includes the preprocessor symbols # and ##.
Nonredefinable Operators
Operator | Name |
---|---|
. | Member selection |
.* | Pointer-to-member selection |
:: | Scope resolution |
? : | Conditional |
# | Preprocessor convert to string |
## | Preprocessor concatenate |
Although overloaded operators are usually called implicitly by the compiler when they are encountered in code, they can be invoked explicitly the same way as any member or nonmember function is called:
Point pt; pt.operator+( 3 ); // Call addition operator to add 3 to pt.
Example
The following example overloads the + operator to add two complex numbers and returns the result.
// operator_overloading.cpp // compile with: /EHsc #include using namespace std; struct Complex < Complex( double r, double i ) : re(r), im(i) <>Complex operator+( Complex &other ); void Display( ) < cout private: double re, im; >; // Operator overloaded using a member function Complex Complex::operator+( Complex &other ) < return Complex( re + other.re, im + other.im ); >int main()
In this section
Перегрузка операторов
Ключевое слово operator объявляет функцию, указывающую, что означает символ оператора при применении к экземплярам класса. Это дает оператору более одного значения — «перегружает» его. Компилятор различает разные значения оператора, проверяя типы его операндов.
Синтаксис
Тип operator operator-symbol(parameter-list)
Комментарии
Функцию большинства встроенных операторов можно переопределить глобально или для отдельных классов. Перегруженные операторы реализуются в виде функции.
Имя перегруженного оператора — operator x, где x — оператор, как показано в следующей таблице. Например, чтобы перегрузить оператор сложения, необходимо определить функцию с именем operator+. Аналогичным образом, чтобы перегрузить оператор сложения или присваивания , +=определите функцию с именем operator+=.
Переопределяемые операторы
Оператор | Имя | Тип |
---|---|---|
, | Запятая | Двоичные данные |
! | Логическое НЕ | Унарный |
!= | Неравенство | Двоичные данные |
% | Модуль | Двоичные данные |
%= | Назначение модуля | Двоичные данные |
& | Побитовое И | Двоичные данные |
& | Взятие адреса | Унарный |
&& | Логическое И | Двоичные данные |
&= | Назначение побитового И | Двоичные данные |
( ) | Вызов функции | — |
( ) | Оператор приведения | Унарный |
* | Умножение | Двоичные данные |
* | Разыменование указателя | Унарный |
*= | Присваивание умножения | Двоичные данные |
+ | Сложение | Двоичные данные |
+ | Унарный плюс | Унарный |
++ | Приращение 1 | Унарный |
+= | Присваивание сложения | Двоичные данные |
— | Вычитание | Двоичные данные |
— | Унарное отрицание | Унарный |
— | Уменьшение 1 | Унарный |
-= | Присваивание вычитания | Двоичные данные |
-> | Выбор члена | Двоичные данные |
->* | Выбор указателя на член | Двоичные данные |
/ | Отдел | Двоичные данные |
/= | Присваивание деления | Двоичные данные |
Меньше чем | Двоичные данные | |
< | Сдвиг влево | Двоичные данные |
Сдвиг влево и присваивание | Двоичные данные | |
Меньше или равно | Двоичные данные | |
= | Назначение | Двоичные данные |
== | Равенство | Двоичные данные |
> | Больше чем | Двоичные данные |
>= | Больше или равно | Двоичные данные |
>> | Сдвиг вправо | Двоичные данные |
>>= | Сдвиг вправо и присваивание | Двоичные данные |
[ ] | Индекс массива | — |
^ | Исключающее ИЛИ | Двоичные данные |
^= | Исключающее ИЛИ/присваивание | Двоичные данные |
| | Побитовое ИЛИ | Двоичные данные |
|= | Назначение побитового включающего ИЛИ | Двоичные данные |
|| | Логическое ИЛИ | Двоичные данные |
~ | Дополнение до единицы | Унарный |
delete | Удалить | — |
new | Создать | — |
операторы преобразования | операторы преобразования | Унарный |
1 Существуют две версии операторов унарного инкремента и декремента: preincrement и postincrement.
Дополнительные сведения см. в статье Общие правила перегрузки операторов . Ограничения для разных категорий перегруженных операторов описываются в следующих разделах.
Операторы, перечисленные в следующей таблице, не могут быть перегружены. Таблица содержит символы # препроцессора и ##.
Непереопределяемые операторы
Оператор | Имя |
---|---|
. | Выбор члена |
.* | Выбор указателя на член |
:: | Разрешение области |
? : | Условная логика |
# | Препроцессор: преобразование в строку |
## | Препроцессор: конкатенация |
Хотя перегруженные операторы обычно называются компилятором неявным образом при их появлении в коде, их можно вызывать и явным образом — точно так же, как и любую функцию-член или функцию, не являющуюся членом.
Point pt; pt.operator+( 3 ); // Call addition operator to add 3 to pt.
Пример
В следующем примере оператор перегружает + два комплексных числа и возвращает результат.
// operator_overloading.cpp // compile with: /EHsc #include using namespace std; struct Complex < Complex( double r, double i ) : re(r), im(i) <>Complex operator+( Complex &other ); void Display( ) < cout private: double re, im; >; // Operator overloaded using a member function Complex Complex::operator+( Complex &other ) < return Complex( re + other.re, im + other.im ); >int main()
В этом разделе
Operator overloading
The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or «overloads» it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.
Syntax
type operator operator-symbol ( parameter-list )
Remarks
You can redefine the function of most built-in operators globally or on a class-by-class basis. Overloaded operators are implemented as functions.
The name of an overloaded operator is operator x, where x is the operator as it appears in the following table. For example, to overload the addition operator, you define a function called operator+. Similarly, to overload the addition/assignment operator, +=, define a function called operator+=.
Redefinable Operators
Operator | Name | Type |
---|---|---|
, | Comma | Binary |
! | Logical NOT | Unary |
!= | Inequality | Binary |
% | Modulus | Binary |
%= | Modulus assignment | Binary |
& | Bitwise AND | Binary |
& | Address-of | Unary |
&& | Logical AND | Binary |
&= | Bitwise AND assignment | Binary |
( ) | Function call | — |
( ) | Cast Operator | Unary |
* | Multiplication | Binary |
* | Pointer dereference | Unary |
*= | Multiplication assignment | Binary |
+ | Addition | Binary |
+ | Unary Plus | Unary |
++ | Increment 1 | Unary |
+= | Addition assignment | Binary |
— | Subtraction | Binary |
— | Unary negation | Unary |
— | Decrement 1 | Unary |
-= | Subtraction assignment | Binary |
-> | Member selection | Binary |
->* | Pointer-to-member selection | Binary |
/ | Division | Binary |
/= | Division assignment | Binary |
Less than | Binary | |
< | Left shift | Binary |
Left shift assignment | Binary | |
Less than or equal to | Binary | |
= | Assignment | Binary |
== | Equality | Binary |
> | Greater than | Binary |
>= | Greater than or equal to | Binary |
>> | Right shift | Binary |
>>= | Right shift assignment | Binary |
[ ] | Array subscript | — |
^ | Exclusive OR | Binary |
^= | Exclusive OR assignment | Binary |
| | Bitwise inclusive OR | Binary |
|= | Bitwise inclusive OR assignment | Binary |
|| | Logical OR | Binary |
~ | One’s complement | Unary |
delete | Delete | — |
new | New | — |
conversion operators | conversion operators | Unary |
1 Two versions of the unary increment and decrement operators exist: preincrement and postincrement.
See General Rules for Operator Overloading for more information. The constraints on the various categories of overloaded operators are described in the following topics:
The operators shown in the following table cannot be overloaded. The table includes the preprocessor symbols # and ##.
Nonredefinable Operators
Operator | Name |
---|---|
. | Member selection |
.* | Pointer-to-member selection |
:: | Scope resolution |
? : | Conditional |
# | Preprocessor convert to string |
## | Preprocessor concatenate |
Although overloaded operators are usually called implicitly by the compiler when they are encountered in code, they can be invoked explicitly the same way as any member or nonmember function is called:
Point pt; pt.operator+( 3 ); // Call addition operator to add 3 to pt.
Example
The following example overloads the + operator to add two complex numbers and returns the result.
// operator_overloading.cpp // compile with: /EHsc #include using namespace std; struct Complex < Complex( double r, double i ) : re(r), im(i) <>Complex operator+( Complex &other ); void Display( ) < cout private: double re, im; >; // Operator overloaded using a member function Complex Complex::operator+( Complex &other ) < return Complex( re + other.re, im + other.im ); >int main()
In this section
General Rules for Operator Overloading
The following rules constrain how overloaded operators are implemented. However, they do not apply to the new and delete operators, which are covered separately.
- You cannot define new operators, such as ..
- You cannot redefine the meaning of operators when applied to built-in data types.
- Overloaded operators must either be a nonstatic class member function or a global function. A global function that needs access to private or protected class members must be declared as a friend of that class. A global function must take at least one argument that is of class or enumerated type or that is a reference to a class or enumerated type. For example:
// rules_for_operator_overloading.cpp class Point < public: Point operator<( Point & ); // Declare a member operator // overload. // Declare addition operators. friend Point operator+( Point&, int ); friend Point operator+( int, Point& ); >; int main()
Note that the meaning of any of the operators can be changed completely. That includes the meaning of the address-of (&), assignment (=), and function-call operators. Also, identities that can be relied upon for built-in types can be changed using operator overloading. For example, the following four statements are usually equivalent when completely evaluated:
var = var + 1; var += 1; var++; ++var;
This identity cannot be relied upon for class types that overload operators. Moreover, some of the requirements implicit in the use of these operators for basic types are relaxed for overloaded operators. For example, the addition/assignment operator, +=, requires the left operand to be an l-value when applied to basic types; there is no such requirement when the operator is overloaded.
For consistency, it is often best to follow the model of the built-in types when defining overloaded operators. If the semantics of an overloaded operator differ significantly from its meaning in other contexts, it can be more confusing than useful.