Arithmetic operators
![]() |
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. |
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 | |||
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); |
|
Índice |
[editar] Explicação
You can help to correct and verify the translation. Click here for instructions.
[editar] Conversões
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.
- 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 tipoOriginal:If either operand has scoped enumeration type, no conversion is performed: the other operand and the return type must have the same typeThe 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 doubleOriginal:Otherwise, if either operand is long double, the other operand is converted to long doubleThe 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 doubleOriginal:Otherwise, if either operand is double, the other operand is converted to doubleThe 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 floatOriginal:Otherwise, if either operand is float, the other operand is converted to floatThe 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ãoOriginal: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 rankThe 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 assinanteOriginal: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 typeThe 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.
-
You can help to correct and verify the translation. Click here for instructions.
[editar] Transborda
onde n é o número de bits de número inteiro que em particular. Por exemplo para unsigned int, adicionando um ao UINT_MAX dá 0, e subtraindo um 0 dá UINT_MAX.
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.
You can help to correct and verify the translation. Click here for instructions.
-ftrapv
GCC e Clang), ou pode ser completamente optimized out by the compiler.-ftrapv
in GCC and Clang), or may be completely optimized out by the compiler.You can help to correct and verify the translation. Click here for instructions.
[editar] Unários operadores aritméticos
A
promovido aritmética tipo e para todos os T
tipo, as assinaturas de função seguintes participar na resolução de sobrecarga:A
and for every type T
, the following function signatures participate in overload resolution:You can help to correct and verify the translation. Click here for instructions.
A operator+(A) |
||
T* operator+(T*) |
||
A operator-(A) |
||
You can help to correct and verify the translation. Click here for instructions.
a
sem sinal, o valor de -a
é 2b-a, onde
b
é o número de bits após a promoção.a
, the value of -a
is 2b-a, where
b
is the number of bits after promotion.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
L
e R
e para cada tipo de objeto T
, as assinaturas de função seguintes participar na resolução de sobrecarga:L
and R
and for every object type T
, the following function signatures participate in overload resolution: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*) |
||
LR
é o resultado de conversões aritméticas usuais sobre L
e R
LR
is the result of usual arithmetic conversions on L
and R
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.
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
i
th de uma matriz, em seguida, as expressõesP+n
,n+P
eP-n
ponteiros são do mesmo tipo, que apontam para oi+n
th,i+n
th e elementoi-n
th da mesma matriz, respectivamente. O resultado da adição do ponteiro pode também ser um indicador de um passado-a-fim (que é, o ponteiroP
tal que os pontos de expressãoP-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 pointerP
points to thei
th element of an array, then the expressionsP+n
,n+P
, andP-n
are pointers of the same type that point to thei+n
th,i+n
th, andi-n
th element of the same array, respectively. The result of pointer addition may also be a one-past-the-end pointer (that is, pointerP
such that the expressionP-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
i
th de uma matriz, e os pontos de ponteiroQ
no elementoj
th da mesma matriz, a expressão tem aP-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 pointerP
points to thei
th element of an array, and the pointerQ
points at thej
th element of the same array, the expressionP-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.
RandomAccessIterator
.RandomAccessIterator
concept.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
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:LA
and RA
and for every pair of promoted integral types LI
and RI
the following function signatures participate in overload resolution: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) |
||
LRx
é o resultado de conversões aritméticas usuais sobre Lx
e Rx
LRx
is the result of usual arithmetic conversions on Lx
and Rx
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.
You can help to correct and verify the translation. Click here for instructions.
- arredondado na aplicação definida (até C++11) direçãoOriginal: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.
a/b
quociente é representible no tipo de resultado, (a/b)*b + a%b == a. Se o segundo operando é zero, o comportamento é indefinido.a/b
is representible in the result type, (a/b)*b + a%b == a. If the second operand is zero, the behavior is undefined.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 inteiraOriginal: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
L
e R
o seguinte assinaturas de função participar na resolução de sobrecarga:L
and R
the following function signatures participate in overload resolution: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) |
||
LR
é o resultado de conversões aritméticas usuais sobre L
e R
LR
is the result of usual arithmetic conversions on L
and R
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() { 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
L
e R
, as assinaturas de função seguintes participar na resolução de sobrecarga:L
and R
, the following function signatures participate in overload resolution:You can help to correct and verify the translation. Click here for instructions.
L operator<<(L, R) |
||
L operator>>(L, R) |
||
You can help to correct and verify the translation. Click here for instructions.
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 * 2bse é representável por o tipo de retorno, caso contrário, o comportamento é indefinido.
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 * 2bif it is representable by the return type, otherwise the behavior is undefined.
You can help to correct and verify the translation. Click here for instructions.
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)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)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> 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
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)
| |
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) | |
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)
|
[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) | |
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) | |
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) | |
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] 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) | |
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) | |
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] 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)
| |
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) | |
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
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)
| |
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) | |
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)
| |
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) | |
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) | |
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) | |
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) | |
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) | |
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) |
[editar] Veja também
Operadores comuns | ||||||
---|---|---|---|---|---|---|
assinamento | incremento descremento |
aritmético | lógico | comparação | acesso de membro |
outros |
a = b |
++a |
+a |
!a |
a == b |
a[b] |
a(...) |
Operadores Especiais | ||||||
static_cast converte um tipo a um outro tipo relacionado |