◐ Shell
clean mode source ↗

Increment/decrement operators - cppreference.com

De cppreference.com

<metanoindex/>

Aumentar / diminuir incrementos operadores ou diminui o valor do objeto.

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.

Operator name Syntax Over​load​able Prototype examples (for class T)
Inside class definition Outside class definition
pre-increment ++a Yes T& T::operator++(); T& operator++(T& a);
pre-decrement --a Yes T& T::operator--(); T& operator--(T& a);
post-increment a++ Yes T T::operator++(int); T operator++(T& a, int);
post-decrement a-- Yes T T::operator--(int); T operator--(T& a, int);

'Notas'

Original:

Notes

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

  • Formas de prefixo do referências internas operadores de retorno e valores postfix formas de retorno e típicos sobrecargas definidas pelo usuário seguem o padrão para que os operadores definidos pelo usuário pode ser usado da mesma forma como o built-ins. No entanto, numa definida pelo utilizador sobrecarga de operador, de qualquer tipo pode ser utilizado como tipo de retorno (incluindo void).

    Original:

    Prefix forms of the built-in operators return references and postfix forms return values, and typical user-defined overloads follow the pattern so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void).

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • O parâmetro é um parâmetro int simulado utilizado para diferenciar entre os pré-e pós-in versões dos operadores. Quando o operador definido pelo usuário postfix é chamado, o valor passado em que o parâmetro é sempre zero, embora possa ser alterada por chamar o operador usando a notação chamada de função, por exemplo, a.operator++(2).

    Original:

    The int parameter is a dummy parameter used to differentiate between pre- and post- in versions of the operators. When the user-defined postfix operator is called, the value passed in that parameter is always zero, although it may be changed by calling the operator using function call notation, e.g. a.operator++(2).

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

Explicação

Pré-incremento e pré-decremento incrementos operadores ou diminui o valor do objeto e retorna uma referência para o resultado.

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.

Pós-incremento e' pós-decrementar cria uma cópia do objeto, aumenta ou diminui o valor do objeto e retorna a cópia de antes do incremento ou decremento.

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.

Built-in operadores de prefixo

Para cada tipo de aritmética opcionalmente volátil qualificado A diferente bool, e para cada P ponteiro opcionalmente volátil qualificado para o tipo de objeto opcionalmente cv-qualificado, as assinaturas de função seguintes participar na resolução de sobrecarga:

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.

<tbody> </tbody>

A& operator++(A&)

bool& operator++(bool&)

(obsoleta)

P& operator++(P&)

A& operator--(A&)

P& operator--(P&)

O operando de um incremento de prefixo embutido ou operador de decremento deve ser um lvalue modificável (não-const referência) de não-tipo boolean aritmética ou ponteiro para completar tipo de objeto. Para estes operandos, o ++x expressão é exatamente equivalente a x+=1, eo --x expressão é exatamente equivalente a x-=1, isto é, o resultado é o operando atualizado, retornou como lvalue, e todas as regras de conversão aritmética e regras aritméticas ponteiro definido para aplicar operadores aritméticos.

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 operadores aritméticos apply.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Se o operando do operador de pré-incremento é de bool tipo, ela é definida como true (obsoleta).

Original:

If the operand of the preincrement operator is of type bool, it is set to true (obsoleta).

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Built-in operadores postfix

Para cada tipo de aritmética opcionalmente volátil qualificado A diferente bool, e para cada P ponteiro opcionalmente volátil qualificado para o tipo de objeto opcionalmente cv-qualificado, as assinaturas de função seguintes participar na resolução de sobrecarga:

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.

<tbody> </tbody>

A operator++(A&, int)

bool operator++(bool&, int)

(obsoleta)

P operator++(P&, int)

A operator--(A&, int)

P operator--(P&, int)

O operando de um incremento postfix integrado ou operador de decremento deve ser um lvalue modificável (não-const referência) de não-tipo boolean aritmética ou ponteiro para completar tipo de objeto. O resultado é uma prvalue, que é uma cópia do valor original do operando. Como efeito colateral, este operador modifica o valor de sua arg argumento como se avaliando arg += 1 ou arg -= 1, para incremento e decremento, respectivamente. Todas as regras de conversão aritmética e regras aritméticas ponteiro definido para operadores aritméticos aplicar.

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 operadores aritméticos apply.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Se o operando do operador postincrement é de bool tipo, ela é definida como true (obsoleta).

Original:

If the operand of the postincrement operator is of type bool, it is set to true (obsoleta).

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Exemplo

#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';
}

Saída:

n = 5
n2 = 2
n3 = 4
n4 = 4

Notas

Por causa dos efeitos colaterais envolvidos, operadores nativos de incremento e decremento deve ser utilizado com cuidado para evitar um comportamento indefinido devido a violações de sequenciamento regras.

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 sequenciamento regras.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Porque uma cópia temporária do objeto é construído durante a operação, incremento pré- ou' pré-decrementar operadores são normalmente mais eficientes em contextos em que o valor retornado não é utilizado.

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.

Biblioteca padrão

Operadores de incremento e decremento são sobrecarregados para muitos tipos da biblioteca padrão. Em particular, cada operador Iterator sobrecargas + + e cada operador BidirectionalIterator sobrecargas -, mesmo que estes operadores são não-ops para o iterador particular.

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.

sobrecargas para tipos aritméticos

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.

aumenta ou diminui o valor atômico por um

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.


(of std::atomic função pública membro) [edit]

aumenta ou diminui a contagem em escala

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.


(of std::chrono::duration função pública membro)

sobrecargas para tipos iterador

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.

avança o iterador

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.


(of std::raw_storage_iterator função pública membro)

avança o iterador

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.


(of std::reverse_iterator função pública membro)

Diminui o iterador

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.


(of std::reverse_iterator função pública membro)
no-op
(of std::back_insert_iterator função pública membro)
no-op
(of std::front_insert_iterator função pública membro)
no-op
(of std::insert_iterator função pública membro)

avança o iterador

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.


(of std::move_iterator função pública membro)

Diminui o iterador

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.


(of std::move_iterator função pública membro)

avança a 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.


(of std::istream_iterator função pública membro)
no-op
(of std::ostream_iterator função pública membro)

avança a 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.


(of std::istreambuf_iterator função pública membro)
no-op
(of std::ostreambuf_iterator função pública membro)

avança a 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.


(of std::regex_iterator função pública membro)

avança a 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.


(of std::regex_token_iterator função pública membro)

Veja também

Precedência do operador

Operadores comuns
assinamento incremento
descremento
aritmético lógico comparação acesso
de membro
outros

a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b

++a --a a++ a--

+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b

!a a && b a || b

a == b a != b a < b a > b a <= b a >= b a <=> b

a[b] *a &a a->b a.b a->*b a.*b

a(...) a, b ? :

Operadores Especiais

static_cast converte um tipo a um outro tipo relacionado
dynamic_cast converte dentro de hierarquias de herança
const_cast adiciona ou remove qualificadores cv
reinterpret_cast converte tipo a tipo não relacionado
C-style cast converte um tipo a um outro por uma mistura de static_cast, const_cast, e reinterpret_cast
new cria objetos com duração de armazenamento dinâmico
delete destrói objetos anteriormente criads pela expressão new e libera área de memória obtida
sizeof pesquisa o tamanho de um tipo
sizeof... pesquisa o tamanho de um pacote de parâmetro (desde C++11)
typeid pesquisa a informação de tipo de um tipo
noexcept checa se uma expressão pode lançar uma exceção (desde C++11)
alignof pesquisa requerimentos de alinhamento de um tipo (desde C++11)