Espaços nominais
Variantes
Acções

Assignment 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
 
Operadores de atribuição modificar o valor do objeto.
Original:
Assignment operators modify 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
basic assignment a = bYes T& T::operator=(const T2& b);N/A
move assignment (C++11)a = rvalueYes T& T::operator=(T2&& b);N/A
addition assignment a += bYes T& T::operator+=(const T2& b);T& operator +=(T& a, const T2& b);
subtraction assignment a -= bYes T& T::operator-=(const T2& b);T& operator -=(T& a, const T2& b);
multiplication assignment a *= bYes T& T::operator*=(const T2& b);T& operator *=(T& a, const T2& b);
division assignment a /= bYes T& T::operator/=(const T2& b);T& operator /=(T& a, const T2& b);
modulo assignment a %= bYes T& T::operator%=(const T2& b);T& operator %=(T& a, const T2& b);
bitwise AND assignment a &= bYes T& T::operator&=(const T2& b);T& operator &=(T& a, const T2& b);
bitwise OR assignment a |= bYes T& T::operator|=(const T2& b);T& operator |=(T& a, const T2& b);
bitwise XOR assignment a ^= bYes T& T::operator^=(const T2& b);T& operator ^=(T& a, const T2& b);
bitwise left shift assignment a <<= bYes T& T::operator<<=(const T2& b);T& operator <<=(T& a, const T2& b);
bitwise right shift assignment a >>= bYes T& T::operator>>=(const T2& b);T& operator >>=(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 embutida atribuição operadores retornar *this, ea maioria das definidas pelo utilizador sobrecargas também retornar *this de modo a 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).
    Original:
    All built-in assignment operators return *this, and most user-defined overloads also return *this 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.
  • 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

' Operador de atribuição de cópia substitui o conteúdo do a objecto com uma cópia dos conteúdos do b (b é não modificada). Para os tipos de classe, esta é uma função de membro especial, descrita no copiar operador de atribuição.
Original:
copy assignment operator replaces the contents of the object a with a copy of the contents of b (b is no modified). For class types, this is a special member function, described in copiar operador de atribuição.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
' Atribuição movimento operador substitui o conteúdo do a objecto com o conteúdo de b, evitando, se possível, a cópia (b pode ser modificado). Para os tipos de classe, esta é uma função de membro especial, descrita no mover operador de atribuição. (desde C++11)
Original:
move assignment operator replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is a special member function, described in mover operador de atribuição. (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.
Para os não-classe tipos, cópia e atribuição movimento são indistinguíveis e são referidos como atribuição direta.
Original:
For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
' Operadores compostos de atribuição substituir o conteúdo dos conteúdos do a objecto com o resultado de uma operação de binário entre o valor anterior de a e o valor de b.
Original:
compound assignment operators replace the contents the contents of the object a with the result of a binary operation between the previous value of a and the value of b.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar]Builtin atribuição direta

Para cada tipo de T, as assinaturas de função seguintes participar na resolução de sobrecarga:
Original:
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.
T*& operator=(T*&, T*);
T*volatile& operator=(T*volatile&, T*);
Para cada enumeração ou ponteiro para T tipo de membro, opcionalmente volátil qualificado, a assinatura da função seguinte participa de resolução de sobrecarga:
Original:
For every enumeration or pointer to member type T, optionally volatile-qualified, the following function signature participates 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.
T& operator=(T&, T );
Para cada par A1 e A2, onde A1 é um tipo de aritmética (opcionalmente volátil qualificado) e A2 é um tipo de aritmética promovido, a assinatura da função seguinte participa de resolução de sobrecarga:
Original:
For every pair A1 and A2, where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates 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.
A1& operator=(A1&, A2);
Para expressões E1 de qualquer tipo escalar T, as seguintes formas adicionais de expressão de atribuição builtin são permitidos:
Original:
For expressions E1 of any scalar type T, the following additional forms of the builtin assignment expression are allowed:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
E1 ={}
(desde C++11)
E1 ={E2}
(desde C++11)
Nota: o acima inclui todos os tipos não-classe, exceto os tipos de referência, tipos de matriz, tipos de função eo void tipo, que não são diretamente atribuíveis.
Original:
Note: the above includes all non-class types except reference types, array types, function types, and the type void, which are not directly assignable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
O operador de atribuição direta espera um lvalue modificável como seu operando esquerdo e retorna um lvalue identificação do operando à esquerda após a modificação. Para os não-classe tipos, o operando direito é convertidos implicitamente primeiro do tipo CV-incondicional do operando à esquerda, e então o seu valor é copiado para o objeto identificado pelo operando esquerdo.
Original:
The direct assignment operator expects a modifiable lvalue as its left operand and returns an lvalue identifying the left operand after modification. For non-class types, the right operand is first convertidos implicitamente to the cv-unqualified type of the left operand, and then its value is copied into the object identified by left operand.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Quando o operando da esquerda é um tipo de referência, o operador de atribuição se aplica ao objeto refere-to.
Original:
When the left operand is a reference type, the assignment operator applies to the referred-to object.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Se a esquerda e os operandos certas identificar objetos sobrepostos, o comportamento é indefinido (a menos que a sobreposição é exata eo tipo é o mesmo)
Original:
If the left and the right operands identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same)
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 direito é um preparei-init-lista
Original:
If the right operand is a braced-init-list
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • o E1 ={} expressão é equivalente a E1 = T(), onde T é o tipo de E1.
    Original:
    the expression E1 ={} is equivalent to E1 = T(), where T is the type of E1.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • o E1 ={E2} expressão é equivalente a E1 = T(E2), onde T é o tipo de E1, excepto que as conversões de estreitamento implícitas são proibidos.
    Original:
    the expression E1 ={E2} is equivalent to E1 = T(E2), where T is the type of E1, except that narrowing implicit conversions are prohibited.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Para os tipos de classes, esta sintaxe gera uma chamada para o operador de atribuição com std::initializer_list como o argumento, seguindo as regras da lista de inicialização
Original:
For class types, this syntax generates a call to the assignment operator with std::initializer_list as the argument, following the rules of lista de inicialização
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar]Exemplo

#include <iostream>int main(){int n =0;// not an assignment n =1;// direct asignmentstd::cout<< n <<' '; n ={};// zero-initialization, then assignmentstd::cout<< n <<' '; n ='a';// integral promotion, then assignmentstd::cout<< n <<' '; n ={'b'};// explicit cast, then assignmentstd::cout<< n <<' '; n =1.0;// floating-point conversion, then assignmentstd::cout<< n <<' ';// n = {1.0}; // compiler error (narrowing conversion)   int& r = n;// not an assignmentint* p;   r =2;// assignment through referencestd::cout<< n <<' '; p =&n;// direct assignment p = nullptr;// null-pointer conversion, then assignment }

Saída:

1 0 97 98 1 2

[editar]Builtin atribuição composto

Para cada par A1 e A2, onde A1 é um tipo de aritmética (opcionalmente volátil qualificado) e A2 é um tipo de aritmética promovido, as assinaturas de função seguintes participar na resolução de sobrecarga:
Original:
For every pair A1 and A2, where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic 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.
A1& operator*=(A1&, A2);
A1& operator/=(A1&, A2);
A1& operator+=(A1&, A2);
A1& operator-=(A1&, A2);
Para cada par I1 e I2, onde I1 é um tipo integral (opcionalmente volátil qualificado) e I2 é um tipo promovido integral, as assinaturas de função seguintes participar na resolução de sobrecarga:
Original:
For every pair I1 and I2, where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral 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.
I1& operator%=(I1&, I2);
I1& operator<<=(I1&, I2);
I1& operator>>=(I1&, I2);
I1& operator&=(I1&, I2);
I1& operator^=(I1&, I2);
I1& operator|=(I1&, I2);
Para cada T opcionalmente cv qualificado tipo de objeto, as assinaturas de função seguintes participar na resolução de sobrecarga:
Original:
For every optionally cv-qualified 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.
T*& operator+=(T*&, std::ptrdiff_t);
T*& operator-=(T*&, std::ptrdiff_t);
T*volatile& operator+=(T*volatile&, std::ptrdiff_t);
T*volatile& operator-=(T*volatile&, std::ptrdiff_t);
{{{1}}}
Original:
{{{2}}}
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar]Exemplo

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

close