Increment/decrement operators
Материал из cppreference.com
|
|
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
Увеличение / уменьшение операторов увеличивает или уменьшает стоимость объекта.
Original:
Increment/decrement operators increments or decrements the value of the object.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
| Operator name | Syntax | Overloadable | Prototype examples (for class T) | |
|---|---|---|---|---|
| Inside class definition | Outside class definition | |||
| pre-increment | ++a
|
Да | T& T::operator++(); | T& operator++(T& a); |
| pre-decrement | --a
|
Да | T& T::operator--(); | T& operator--(T& a); |
| post-increment | a++
|
Да | T T::operator++(int); | T operator++(T& a, int); |
| post-decrement | a--
|
Да | T T::operator--(int); | T operator--(T& a, int); |
| ||||
[править] Объяснение
Преинкремента и предекремента операторов увеличивает или уменьшает стоимость объекта и возвращает ссылку на результат.
Original:
pre-increment and pre-decrement operators increments or decrements the value of the object and returns a reference to the result.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Пост-инкремент и пост-декремент создает копию объекта, увеличивает или уменьшает стоимость объекта и возвращает копию еще до увеличения или уменьшения.
Original:
post-increment and post-decrement creates a copy of the object, increments or decrements the value of the object and returns the copy from before the increment or decrement.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Встроенный префикса оператора
Для каждого необязательно летучих квалифицированных арифметический тип
A кроме bool, и для каждого необязательно летучих квалифицированных указатель P для возможного резюме квалифицированных тип объекта, следующие функции подписи участие в разрешении перегрузкиOriginal:
For every optionally volatile-qualified arithmetic type
A other than bool, and for every optionally volatile-qualified pointer P to optionally cv-qualified object type, the following function signatures participate in overload resolution:The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
| A& operator++(A&) |
||
| bool& operator++(bool&) |
(устарело) | |
| P& operator++(P&) |
||
| A& operator--(A&) |
||
| P& operator--(P&) |
||
Операнд встроенным прирост или уменьшение префикса оператора должны быть изменяемыми именующее (неконстантные ссылка) не-логический тип арифметической или указатель для завершения тип объекта. Для этих операнды, выражения ++x в точности эквивалентен x+=1, и выражение --x в точности эквивалентен x-=1, то есть, в результате обновленный операнд, возвращаются как именующее, и все арифметические правила преобразования и правила арифметики указателей определены для арифметических операторов применять.
Original:
The operand of a built-in prefix increment or decrement operator must be a modifiable lvalue (non-const reference) of non-boolean arithmetic type or pointer to complete object type. For these operands, the expression ++x is exactly equivalent to x+=1, and the expression --x is exactly equivalent to x-=1, that is, the result is the updated operand, returned as lvalue, and all arithmetic conversion rules and pointer arithmetic rules defined for арифметических операторов apply.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Если операнд прединкремента оператор типа bool, он установлен на true (устарело).
Original:
If the operand of the preincrement operator is of type bool, it is set to true (устарело).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Встроенный постфиксными
Для каждого необязательно летучих квалифицированных арифметический тип
A кроме bool, и для каждого необязательно летучих квалифицированных указатель P для возможного резюме квалифицированных тип объекта, следующие функции подписи участие в разрешении перегрузкиOriginal:
For every optionally volatile-qualified arithmetic type
A other than bool, and for every optionally volatile-qualified pointer P to optionally cv-qualified object type, the following function signatures participate in overload resolution:The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
| A operator++(A&, int) |
||
| bool operator++(bool&, int) |
(устарело) | |
| P operator++(P&, int) |
||
| A operator--(A&, int) |
||
| P operator--(P&, int) |
||
Операнд встроенным постфиксный оператор увеличения или уменьшения должны быть изменяемыми именующее (неконстантные ссылка) не-логический тип арифметической или указатель для завершения тип объекта. В результате prvalue, который является копией исходного значения операнда. Как побочный эффект, этот оператор изменяет значение своего аргумента
arg, как будто оценивая arg += 1 или arg -= 1, для увеличения и уменьшения соответственно. Все арифметические правила преобразования и правила арифметики указателей определены для арифметических операторов применять.Original:
The operand of a built-in postfix increment or decrement operator must be a modifiable lvalue (non-const reference) of non-boolean arithmetic type or pointer to complete object type. The result is a prvalue, which is a copy the original value of the operand. As a side-effect, this operator modifies the value of its argument
arg as if by evaluating arg += 1 or arg -= 1, for increment and decrement respectively. All arithmetic conversion rules and pointer arithmetic rules defined for арифметических операторов apply.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Если операнд постинкремента оператор типа bool, он установлен на true (устарело).
Original:
If the operand of the postincrement operator is of type bool, it is set to true (устарело).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Пример
#include <iostream> int main() { int n = 1; int n2 = ++n; int n3 = ++ ++n; int n4 = n++; // int n5 = n++ ++; // compile error // int n5 = n + ++n; // undefined behavior std::cout << "n = " << n << '\n' << "n2 = " << n2 << '\n' << "n3 = " << n3 << '\n' << "n4 = " << n4 << '\n'; }
Вывод:
n = 5 n2 = 2 n3 = 4 n4 = 4
[править] Notes
Из-за побочных эффектах, связанных, встроенных операторов инкремента и декремента должны использоваться с осторожностью, чтобы избежать неопределенного поведения вследствие нарушения последовательности правил.
Original:
Because of the side-effects involved, built-in increment and decrement operators must be used with care to avoid undefined behavior due to violations of последовательности правил.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Потому что временная копия объекта построены во время операции, преинкремента или предекремента операторы, как правило, более эффективны в условиях, когда возвращаемое значение не используется.
Original:
Because a temporary copy of the object is constructed during the operation, pre-increment or pre-decrement operators are usually more efficient in contexts where the returned value is not used.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Стандартные библиотеки
Операторы инкремента и декремента перегружены для многих стандартных типов библиотек. В частности, каждый оператор
Iterator перегрузок + +, и каждый оператор BidirectionalIterator перегрузки - даже если эти операторы холостого хода для данного итератора.Original:
Increment and decrement operators are overloaded for many standard library types. In particular, every
Iterator overloads operator++ and every BidirectionalIterator overloads operator--, even if those operators are no-ops for the particular iterator.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Original: overloads for arithmetic types The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | |
| увеличивает или уменьшает атомный значение на единицу Original: increments or decrements the atomic value by one The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::atomic)
| |
| увеличивает или уменьшает количество тиков Original: increments or decrements the tick count The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::chrono::duration)
| |
Original: overloads for iterator types The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | |
| перемещает итератор Original: advances the iterator The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::raw_storage_iterator)
| |
| перемещает итератор Original: advances the iterator The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::reverse_iterator)
| |
| Уменьшает итератор Original: decrements the iterator The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::reverse_iterator)
| |
| no-op (public функция-член std::back_insert_iterator)
| |
| no-op (public функция-член std::front_insert_iterator)
| |
| no-op (public функция-член std::insert_iterator)
| |
| перемещает итератор Original: advances the iterator The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::move_iterator)
| |
| Уменьшает итератор Original: decrements the iterator The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::move_iterator)
| |
| авансы istream_iterator Original: advances the istream_iterator The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::istream_iterator)
| |
| no-op (public функция-член std::ostream_iterator)
| |
| авансы istreambuf_iterator Original: advances the istreambuf_iterator The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::istreambuf_iterator)
| |
| no-op (public функция-член std::ostreambuf_iterator)
| |
| авансы regex_iterator Original: advances the regex_iterator The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::regex_iterator)
| |
| авансы regex_token_iterator Original: advances the regex_token_iterator The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член std::regex_token_iterator)
| |
[править] См. также
| Common operators | ||||||
|---|---|---|---|---|---|---|
| назначение | incrementNJdecrement | арифметики | логичной | сравнение | memberNJaccess | другие |
|
a = b |
++a |
+a |
!a |
a == b |
a[b] |
a(...) |
| Special operators | ||||||
|
static_cast преобразует один тип на другой совместимый
типа Original: static_cast converts one type to another compatible type The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. dynamic_cast преобразует виртуальный базовый класс для производных class
Original: dynamic_cast converts virtual base class to derived class The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. const_cast преобразует тип совместимого типа с различными cv qualifiers
Original: The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. reinterpret_cast преобразует тип несовместимы type
Original: reinterpret_cast converts type to incompatible type The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. new выделяет memory
Original: new allocates memory The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. delete освобождает memory
Original: delete deallocates memory The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. sizeof запрашивает размер type
Original: sizeof queries the size of a type The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. sizeof... запрашивает размер Параметр пакета (начиная с C++11)
Original: The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. typeid запрашивает сведения о типе type
Original: typeid queries the type information of a type The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. noexcept проверяет выражение может вызвать исключение (начиная с C++11)
Original: The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. alignof запросов выравнивание требований типа (начиная с C++11)
Original: alignof queries alignment requirements of a type (начиная с C++11) The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||||