Espaços nominais
Variantes
Acções

Arithmetic operators

Da cppreference.com
< cpp‎ | language

 
 
Linguagem C++
Tópicos gerais
Original:
General topics
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Controle de fluxo
Original:
Flow control
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Declarações execução condicional
Original:
Conditional execution statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Instruções de iteração
Original:
Iteration statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Ir declarações
Original:
Jump statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funções
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaração da função
lambda declaração da função
modelo de função
linha especificador
especificações de exceção (obsoleta)
noexcept especificador (C++11)
Exceções
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Namespaces
Original:
Namespaces
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
decltype specifier (C++11)
Especificadores
Original:
Specifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
cv especificadores
armazenamento duração especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialização
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Literais
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expressões
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representações alternativas
Utilitários
Original:
Utilities
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
typedef declaration
tipo de alias declaração (C++11)
atributos (C++11)
Conversões
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversões implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
Elenco C-estilo e funcional
Alocação de memória
Original:
Memory allocation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classes
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classe propriedades específicas de função
Original:
Class-specific function properties
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funções membro especiais
Original:
Special member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Modelos
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
modelo de classe
modelo de função
especialização de modelo
pacotes de parâmetros (C++11)
Diversos
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Assembly embutido
 
Retorna o resultado da operação aritmética específica.
Original:
Returns the result of specific arithmetic operation.
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
unary plus +a Yes T T::operator+() const; T operator+(const T &a);
unary minus -a Yes T T::operator-() const; T operator-(const T &a);
addition a + b Yes T T::operator+(const T2 &b) const; T operator+(const T &a, const T2 &b);
subtraction a - b Yes T T::operator-(const T2 &b) const; T operator-(const T &a, const T2 &b);
multiplication a * b Yes T T::operator*(const T2 &b) const; T operator*(const T &a, const T2 &b);
division a / b Yes T T::operator/(const T2 &b) const; T operator/(const T &a, const T2 &b);
modulo a % b Yes T T::operator%(const T2 &b) const; T operator%(const T &a, const T2 &b);
bitwise NOT ~a Yes T T::operator~() const; T operator~(const T &a);
bitwise AND a & b Yes T T::operator&(const T2 &b) const; T operator&(const T &a, const T2 &b);
bitwise OR a | b Yes T T::operator|(const T2 &b) const; T operator|(const T &a, const T2 &b);
bitwise XOR a ^ b Yes T T::operator^(const T2 &b) const; T operator^(const T &a, const T2 &b);
bitwise left shift a << b Yes T T::operator<<(const T2 &b) const; T operator<<(const T &a, const T2 &b);
bitwise right shift a >> b Yes T T::operator>>(const T2 &b) const; T operator>>(const T &a, const T2 &b);
'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.
  • Todos os valores internos operadores de retorno, e mais definidos pelo utilizador sobrecargas também devolver valores, de modo que os operadores definidos pelo utilizador podem ser usados ​​da mesma maneira 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). Na inserção fluxo particular, e sobrecargas fluxo de extração de operator<< e operator>> retorno T&.
    Original:
    All built-in operators return values, and most user-defined overloads also return values 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). In particular, stream insertion and stream extraction overloads of operator<< and operator>> return T&.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • T2 pode ser de qualquer tipo, incluindo T
    Original:
    T2 can be any type including T
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

Índice

[editar] Explicação

Todos os operadores aritméticos calcular o resultado da operação aritmética específica e retorna seu resultado. Os argumentos não são modificados.
Original:
All arithmetic operators compute the result of specific arithmetic operation and returns its result. The arguments are not modified.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Conversões

Se o operando passado para um operador aritmético é integral ou tipo de enumeração sem escopo, em seguida, antes de qualquer outra ação (mas depois lvalue para rvalue-conversão, se for o caso), o operando sofre promoção integral. Se um operando tem matriz ou função, tipo matriz para ponteiro e função para ponteiro-conversões são aplicadas.
Original:
If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes promoção integral. If an operand has array or function type, array-to-pointer and function-to-pointer conversions are applied.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Para os operadores binários (exceto turnos), se os operandos promovidas têm diferentes tipos, conjunto adicional de conversões implícitas é aplicada, conhecido como conversões aritméticas usuais com o objetivo de produzir o tipo comum (também acessível via o traço tipo std::common_type)
Original:
For the binary operators (except shifts), if the promoted operands have different types, additional set of implicit conversions is applied, known as usual arithmetic conversions with the goal to produce the common type (also accessible via the std::common_type type trait)
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 tem o tipo de enumeração escopo, nenhuma conversão é feita: o outro operando eo tipo de retorno deve ter o mesmo tipo
    Original:
    If either operand has scoped enumeration type, no conversion is performed: the other operand and the return type must have the same type
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Caso contrário, se o operando é long double, o outro operando é convertido para long double
    Original:
    Otherwise, if either operand is long double, the other operand is converted to long double
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Caso contrário, se o operando é double, o outro operando é convertido para double
    Original:
    Otherwise, if either operand is double, the other operand is converted to double
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Caso contrário, se o operando é float, o outro operando é convertido para float
    Original:
    Otherwise, if either operand is float, the other operand is converted to float
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Caso contrário, o operando tem o tipo inteiro (porque bool, char, char16_t, char32_t, wchar_t, e enumeração sem escopo foram promovidos neste ponto) e conversões integrais são aplicadas para produzir o tipo comum, como segue:
    Original:
    Otherwise, the operand has integer type (because bool, char, char16_t, char32_t, wchar_t, and unscoped enumeration were promoted at this point) and conversões integrais are applied to produce the common type, as follows:
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Se ambos os operandos são assinados ou ambos estão sem sinal, o operando com menor grau de conversão' é convertido para o operando com a maior rango inteiro conversão
    Original:
    If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Caso contrário, se a posição do operando sem sinal de conversão é maior ou igual ao grau de conversão do operando assinado, o operando assinado é convertido para o tipo do operando sem sinal de.
    Original:
    Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Caso contrário, se o assinado tipo operando pode representar todos os valores do operando sem sinal, o operando sem sinal é convertido para o tipo do operando assinante
    Original:
    Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signer operand's type
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Caso contrário, ambos os operandos são convertidos para a contrapartida unsigned do tipo operando assinado de.
    Original:
    Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
O posto de conversão' acima aumenta a fim bool, signed char, short, int, long, long long. A classificação de qualquer tipo sem sinal é igual à classificação do tipo correspondente assinado. O posto de char é igual ao posto de signed char e unsigned char. As fileiras de char16_t, char32_t, e wchar_t são iguais para as fileiras dos seus tipos base.
Original:
The conversion rank above increases in order bool, signed char, short, int, long, long long. The rank of any unsigned type is equal to the rank of the corresponding signed type. The rank of char is equal to the rank of signed char and unsigned char. The ranks of char16_t, char32_t, and wchar_t are equal to the ranks of their underlying types.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Transborda

Aritmético inteiro sem sinal é sempre executada modulo 2n
onde n é o número de bits de número inteiro que em particular. Por exemplo para unsigned int, adicionando um ao UINT_MAX0, e subtraindo um 0UINT_MAX.
Original:
Unsigned integer arithmetic is always performed modulo 2n
where n is the number of bits in that particular integer. E.g. for unsigned int, adding one to UINT_MAX gives 0, and subtracting one from 0 gives UINT_MAX.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Quando assinou transborda aritmética inteira de operação (o resultado não se encaixa no tipo de resultado), o comportamento é indefinido: pode envolver em torno de acordo com as regras da representação (normalmente complemento para 2), pode prender em algumas plataformas ou devido ao compilador (por exemplo, opções de -ftrapv GCC e Clang), ou pode ser completamente optimized out by the compiler.
Original:
When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined: it may wrap around according to the rules of the representation (typically 2's complement), it may trap on some platforms or due to compiler options (e.g. -ftrapv in GCC and Clang), or may be completely optimized out by the compiler.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Unários operadores aritméticos

Para cada A promovido aritmética tipo e para todos os T tipo, as assinaturas de função seguintes participar na resolução de sobrecarga:
Original:
For every promoted arithmetic type A and for every type T, 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.
A operator+(A)
T* operator+(T*)
A operator-(A)
O unário builtin mais retorna o valor de seu operando. A única situação em que não é uma no-op é quando o operando tem tipo integral ou tipo de enumeração sem escopo, que é alterado pela promoção integral, por exemplo, converte para char int ou se o operador é sujeito a lvalue-to-rvalue, matriz para ponteiro, ou função de ponteiro-de conversão.
Original:
The builtin unary plus operator returns the value of its operand. The only situation where it is not a no-op is when the operand has integral type or unscoped enumeration type, which is changed by integral promotion, e.g, it converts char to int or if the operand is subject to lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversion.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
O unário builtin menos operador calcula o negativo de seu operando. Para a sem sinal, o valor de -a é 2b
-a
, onde b é o número de bits após a promoção.
Original:
The builtin unary minus operator calculates the negative of its operand. For unsigned a, the value of -a is 2b
-a
, where b is the number of bits after promotion.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
#include <iostream>
int main()
{
    char c = 0x6a;
    int n1 = 1;
    unsigned char n2 = 1;
    unsigned int n3 = 1;
    std::cout << "char: " << c << " int: " << +c << '\n'
              << "-1, where 1 is signed: " << -n1 << '\n'
              << "-1, where 1 is unsigned char: " << -n2 << '\n'
              << "-1, where 1 is unsigned int: " << -n3 << '\n';
    char a[3];
    std::cout << "size of array: " << sizeof a << '\n'
              << "size of pointer: " << sizeof +a << '\n';
}

Saída:

char: j int: 106
-1, where 1 is signed: -1
-1, where 1 is unsigned char: -1
-1, where 1 is unsigned int: 4294967295
size of array: 3
size of pointer: 8

[editar] Operadores aditivos

Para cada par de tipos aritméticos promovidas L e R e para cada tipo de objeto T, as assinaturas de função seguintes participar na resolução de sobrecarga:
Original:
For every pair of promoted arithmetic types L and R and for every object type T, 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.
LR operator+(L, R)
LR operator-(L, R)
T* operator+(T*, std::ptrdiff_t)
T* operator+(std::ptrdiff_t, T*)
T* operator-(T*, std::ptrdiff_t)
std::ptrdiff_t operator-(T*, T*)
onde LR é o resultado de conversões aritméticas usuais sobre L e R
Original:
where LR is the result of usual arithmetic conversions on L and R
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Com operandos de aritmética ou tipo de enumeração, o resultado do binário positivo é a soma dos operandos (após converesions aritméticos usuais), e o resultado do binário negativo operador é o resultado da subtracção do segundo operando do primeiro (depois de conversões aritméticas usuais ).
Original:
With operands of arithmetic or enumeration type, the result of binary plus is the sum of the operands (after usual arithmetic converesions), and the result of the binary minus operator is the result of subtracting the second operand from the first (after usual arithmetic conversions).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Se qualquer um dos operadores é um ponteiro, as seguintes regras se aplicam:
Original:
If any of the operands is a pointer, the following rules apply:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • Um ponteiro para não-array objecto é tratado como um ponteiro para o primeiro elemento de uma matriz com o tamanho 1.
    Original:
    A pointer to non-array object is treated as a pointer to the first element of an array with size 1.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Se o ponteiro aponta para o elemento P ith de uma matriz, em seguida, as expressões P+n, n+P e P-n ponteiros são do mesmo tipo, que apontam para o i+nth, i+nth e elemento i-nth da mesma matriz, respectivamente. O resultado da adição do ponteiro pode também ser um indicador de um passado-a-fim (que é, o ponteiro P tal que os pontos de expressão P-1 ao último elemento da matriz). Quaisquer outras situações (isto é, tenta gerar um ponteiro que não está a apontar para um elemento da mesma matriz ou um após o final) invocar um comportamento indefinido.
    Original:
    If the pointer P points to the ith element of an array, then the expressions P+n, n+P, and P-n are pointers of the same type that point to the i+nth, i+nth, and i-nth element of the same array, respectively. The result of pointer addition may also be a one-past-the-end pointer (that is, pointer P such that the expression P-1 points to the last element of the array). Any other situations (that is, attempts to generate a pointer that isn't pointing at an element of the same array or one past the end) invoke undefined behavior.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Se o ponteiro aponta para o elemento P ith de uma matriz, e os pontos de ponteiro Q no elemento jth da mesma matriz, a expressão tem a P-Q i-j valor, se o valor for apropriado para std::ptrdiff_t. Ambos os operandos deve apontar para os elementos da mesma matriz (ou um passado no final), caso contrário, o comportamento é indefinido. Se o resultado não se encaixa em std::ptrdiff_t, o comportamento é indefinido.
    Original:
    If the pointer P points to the ith element of an array, and the pointer Q points at the jth element of the same array, the expression P-Q has the value i-j, if the value fits in std::ptrdiff_t. Both operands must point to the elements of the same array (or one past the end), otherwise the behavior is undefined. If the result does not fit in std::ptrdiff_t, the behavior is undefined.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Se o valor 0 é adicionado ou subtraído de um ponteiro, o resultado é o ponteiro, inalterada. Se dois ponteiros de ponto no mesmo objecto ou são ambos um após o final da mesma matriz, ou ambos são ponteiros nulos, então o resultado de subtração é igual a (std::ptrdiff_t)0.
    Original:
    If the value 0 is added or subtracted from a pointer, the result is the pointer, unchanged. If two pointers point at the same object or are both one past the end of the same array, or both are null pointers, then the result of subtraction is equal to (std::ptrdiff_t)0.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Estes operadores aritméticos ponteiro permitir ponteiros para satisfazer o conceito RandomAccessIterator.
Original:
These pointer arithmetic operators allow pointers to satisfy the RandomAccessIterator concept.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
#include <iostream>
int main()
{
    char c = 2;
    unsigned int un = 2;
    int  n = -10;
    std::cout <<  " 2 + (-10), where 2 is a char    = " << c + n << '\n'
              <<  " 2 + (-10), where 2 is unsigned  = " << un + n << '\n'
              <<  " -10 - 2.12  = " << n - 2.12 << '\n';
 
    char a[4] = {'a', 'b', 'c', 'd'};
    char* p = &a[1];
    std::cout << "Pointer addition examples: " << *p << *(p + 2)
              << *(2 + p) << *(p - 1) << '\n';
    char* p2 = &a[4];
    std::cout << "Pointer difference: " << p2 - p << '\n';
}

Saída:

2 + (-10), where 2 is a char    = -8
 2 + (-10), where 2 is unsigned  = 4294967288
 -10 - 2.12  = -12.12
Pointer addition examples: bdda
Pointer difference: 3

[editar] Operadores multiplicativos

Para cada par de tipos aritméticos promovidas LA e RA e para cada par de promovidos tipos integrais LI e RI o seguinte assinaturas de função participar na resolução de sobrecarga:
Original:
For every pair of promoted arithmetic types LA and RA and for every pair of promoted integral types LI and RI 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.
LRA operator*(LA, RA)
LRA operator/(LA, RA)
LRI operator%(LI, RI)
onde LRx é o resultado de conversões aritméticas usuais sobre Lx e Rx
Original:
where LRx is the result of usual arithmetic conversions on Lx and Rx
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
O * operador binário executa multiplicação de seus operandos (após conversões aritméticas usuais).
Original:
The binary operator * performs multiplication of its operands (after usual arithmetic conversions).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
O operador binário / divide o primeiro operando pelo segundo (depois de conversões aritméticas usuais). Se o segundo operando é zero, o comportamento é indefinido. Para operandos integrais, produz o quociente algébrica
Original:
The binary operator / divides the first operand by the second (after usual arithmetic conversions).If the second operand is zero, the behavior is undefined. For integral operands, it yields the algebraic quotient
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • arredondado na aplicação definida (até C++11) direção
    Original:
    rounded in implementation-defined direction (até C++11)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • com qualquer parte fracionária descartado (truncado para zero) (desde C++11)
    Original:
    with any fractional part discarded (truncated towards zero) (desde C++11)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
O operador binário% produz o resto da divisão do primeiro operando pelo segundo (depois de conversões aritméticas usuais). Se o a/b quociente é representible no tipo de resultado, (a/b)*b + a%b == a. Se o segundo operando é zero, o comportamento é indefinido.
Original:
The binary operator % yields the remainder of the division of the first operand by the second (after usual arithmetic conversions). If the quotient a/b is representible in the result type, (a/b)*b + a%b == a. If the second operand is zero, the behavior is undefined.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • se um ou ambos os operandos são negativos, o sinal de que o restante é definida pela implementação, uma vez que depende da direção arredondamento de (até C++11) divisão inteira
    Original:
    if one or both operands are negative, the sign of the remainder is implementation-defined, as it depends on the rounding direction of integer division (até C++11)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
#include <iostream>
int main()
{
    char c = 2;
    unsigned int un = 2;
    int  n = -10;
    std::cout <<  "2 * (-10), where 2 is a char    = " << c * n << '\n'
              <<  "2 * (-10), where 2 is unsigned  = " << un * n << '\n'
              <<  "-10 / 2.12  = " << n / 2.12 << '\n'
              <<  "-10 / 21  = " << n / 21 << '\n'
              <<  "-10 % 21  = " << n % 21 << '\n';
}

Saída:

2 * (-10), where 2 is a char    = -20
2 * (-10), where 2 is unsigned  = 4294967276
-10 / 2.12  = -4.71698
-10 / 21  = 0
-10 % 21  = -10

[editar] Lógicos operadores bit a bit

Para cada par de promovidos tipos integrais L e R o seguinte assinaturas de função participar na resolução de sobrecarga:
Original:
For every pair of promoted integral types L and R 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.
R operator~(R)
LR operator&(L, R)
LR operator^(L, R)
LR operator|(L, R)
onde LR é o resultado de conversões aritméticas usuais sobre L e R
Original:
where LR is the result of usual arithmetic conversions on L and R
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
O resultado do operador ~ é o NÃO bitwise valor (um complemento) do argumento (após a promoção). O resultado do operador e é o bit a bit e valor dos operandos (após conversões aritméticas usuais). O resultado do operador
Original:
é o bit a bit ou o valor dos operandos (depois de conversões aritméticas usuais). O resultado do operador ^ é o valor XOR bit a bit dos operandos (depois de conversões aritméticas usuais)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
#include <iostream>
int main()
{
    std::cout << std::hex << std::showbase;
    uint16_t mask = 0x00f0;
    uint32_t a = 0x12345678;
    std::cout << "Value: " << a << " mask: " << mask << '\n'
              << "Setting bits: " << (a

Saída:

Value: 0x12345678 mask: 0xf0
Setting bits: 0x123456f8
Clearing bits: 0x12345608
Selecting bits: 0x70

[editar] Mudança de operadores bit a bit

Para cada par de promovidos tipos integrais L e R, as assinaturas de função seguintes participar na resolução de sobrecarga:
Original:
For every pair of promoted integral types L and R, 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.
L operator<<(L, R)
L operator>>(L, R)
Os operandos do built-in operadores de deslocamento bit a bit têm tipos ou integrais ou do tipo de enumeração sem escopo. Promoções integrais são realizados em ambos os operandos antes da avaliação. O tipo de retorno é o tipo do operando à esquerda depois de promoções integal.
Original:
The operands of the built-in bitwise shift operators have either integral types or unscoped enumeration type. Integral promotions are performed on both operands before evaluation. The return type is the type of the left operand after integal promotions.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Para a sem sinal, o valor de a << b é o valor de a * 2b
, reduzido modulo valor máximo do tipo de retorno mais 1 (isto é, deslocamento para a esquerda bit a bit é executada e os bits que são deslocados para fora do tipo de destino são descartados). Para a assinado, o valor de a << b é a * 2b
se é representável por o tipo de retorno, caso contrário, o comportamento é indefinido.
Original:
For unsigned a, the value of a << b is the value of a * 2b
, reduced modulo maximum value of the return type plus 1 (that is, bitwise left shift is performed and the bits that get shifted out of the destination type are discarded). For signed a, the value of a << b is a * 2b
if it is representable by the return type, otherwise the behavior is undefined.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Para a unsigned e para a assinado com valores não-negativos, o valor de a >> b é a parte inteira do a/2b
. Para a negativa, o valor do a >> b é definida pela implementação (na maioria das implementações, este executa deslocamento aritmético à direita, de forma que o resultado continua a ser negativo)
Original:
For unsigned a and for signed a with nonnegative values, the value of a >> b is the integer part of a/2b
. For negative a, the value of a >> b is implementation-defined (in most implementations, this performs arithmetic right shift, so that the result remains negative)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Em qualquer caso, se o valor do operando à direita é negativo ou é maior ou igual ao número de bits na operando promovido esquerda, o comportamento é indefinido.
Original:
In any case, if the value of the right operand is negative or is greater or equal to the number of bits in the promoted left operand, the behavior is undefined.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
#include <iostream>
enum {ONE=1, TWO=2};
int main()
{
    std::cout << std::hex << std::showbase;
    char c = 0x10;
    unsigned long long ull = 0x123;
    std::cout << "0x123 << 1 = " << (ull << 1) << '\n'
              << "0x123 << 63 = " << (ull << 63) << '\n' // overflow in unsigned
              << "0x10 << 10 = " << (c << 10) << '\n';   // char is promoted to int
    long long ll = -1000;
    std::cout << std::dec << "-1000 >> 1 = " << (ll >> ONE) << '\n';
}

Saída:

0x123 << 1 = 0x246
0x123 << 63 = 0x8000000000000000
0x10 << 10 = 0x4000
-1000 >> 1 = -500

[editar] Biblioteca padrão

Os operadores aritméticos são sobrecarregados para muitos tipos da biblioteca padrão.
Original:
Arithmetic operators are overloaded for many standard library types.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Unários operadores aritméticos

implementa + unário e - unário
Original:
implements unary + and unary -
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) [edit]
aplica operadores unários aos números complexos
Original:
applies unary operators to complex numbers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]
aplica-se um operador unário aritmética para cada elemento da valarray
Original:
applies a unary arithmetic operator to each element of the valarray
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

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

[editar] Operadores aditivos

modifica o ponto no tempo determinado pela duração
Original:
modifies the time point by the given duration
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]
concatena duas strings ou uma String e um char
Original:
concatenates two strings or a string and a char
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]
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)
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)
executa aritmética de números complexos em dois valores complexos ou um complexo e um escalar
Original:
performs complex number arithmetics on two complex values or a complex and a scalar
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]
aplica-se operadores binários para cada elemento de duas valarrays, ou um valarray e um valor
Original:
applies binary operators to each element of two valarrays, or a valarray and a value
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]

[editar] Operadores multiplicativos

implementa operações aritméticas com durações como argumentos
Original:
implements arithmetic operations with durations as arguments
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]
executa aritmética de números complexos em dois valores complexos ou um complexo e um escalar
Original:
performs complex number arithmetics on two complex values or a complex and a scalar
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]
aplica-se operadores binários para cada elemento de duas valarrays, ou um valarray e um valor
Original:
applies binary operators to each element of two valarrays, or a valarray and a value
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]

[editar] Lógicos operadores bit a bit

executa binário AND, OR, XOR e NOT
Original:
performs binary AND, OR, XOR and NOT
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(of std::bitset função pública membro) [edit]
executa operações lógicas sobre bitsets binários
Original:
performs binary logic operations on bitsets
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função) [edit]
aplica-se um operador unário aritmética para cada elemento da valarray
Original:
applies a unary arithmetic operator to each element of the valarray
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(of std::valarray função pública membro)
aplica-se operadores binários para cada elemento de duas valarrays, ou um valarray e um valor
Original:
applies binary operators to each element of two valarrays, or a valarray and a value
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função)

[editar] Mudança de operadores bit a bit

aplica-se operadores binários para cada elemento de duas valarrays, ou um valarray e um valor
Original:
applies binary operators to each element of two valarrays, or a valarray and a value
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função)
realiza esquerda binário mudança e deslocamento para a direita
Original:
performs binary shift left and shift right
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

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

[editar] Fluxo de inserção / extração de operadores

Ao longo da biblioteca padrão, operadores de deslocamento bit a bit são geralmente sobrecarregado com I / O fluxo (std::ios_base& ou uma das classes derivadas dele) como ambos operando a esquerda e tipo de retorno. Esses operadores são conhecidos como inserção fluxo e' extração fluxo operadores:
Original:
Throughout the standard library, bitwise shift operators are commonly overloaded with I/O stream (std::ios_base& or one of the classes derived from it) as both the left operand and return type. Such operators are known as stream insertion and stream extraction operators:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
extratos dados formatados
Original:
extracts formatted data
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(of std::basic_istream função pública membro) [edit]
extrai os caracteres e matrizes de caracteres
Original:
extracts characters and character arrays
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]
insere dados formatados
Original:
inserts formatted data
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(of std::basic_ostream função pública membro) [edit]
inserções de dados de caracteres
Original:
inserts character data
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função) [edit]
serializa e desserializa um número complexo
Original:
serializes and deserializes a complex number
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]
realiza fluxo de entrada e saída de bitsets
Original:
performs stream input and output of bitsets
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função) [edit]
executa fluxo de I / O em cordas
Original:
performs stream I/O on strings
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]
executa fluxo de entrada e saída em pseudo-aleatório motor número
Original:
performs stream input and output on pseudo-random number engine
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função) [edit]
executa fluxo de entrada e saída em pseudo-aleatório distribuição de números
Original:
performs stream input and output on pseudo-random number distribution
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função) [edit]

[editar] 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)