◐ Shell
clean mode source ↗

Logical operators - cppreference.com

De cppreference.com

<metanoindex/>

Returns the result of a boolean operation.

Operator name Syntax Over​load​able Prototype examples (for class T)
Inside class definition Outside class definition
negation not a

!a

Yes bool T::operator!() const; bool operator!(const T &a);
AND a and b

a && b

Yes bool T::operator&&(const T2 &b) const; bool operator&&(const T &a, const T2 &b);
inclusive OR a or b

a || b

Yes bool T::operator||(const T2 &b) const; bool 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.

  • The keyword-like forms (and,or,not) and the symbol-like forms (&&,||,!) can be used interchangeably (See representações alternativas)
  • Todos os operadores internos bool de retorno, e a maioria das definidas pelo utilizador sobrecargas também retornar bool de modo a que os operadores definidos pelo utilizador podem ser usados ​​da mesma maneira como o ins embutido. 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 operators return bool, and most user-defined overloads also return bool 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.

  • Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands

Explicação

The logical operators apply logic functions (NOT, AND, and inclusive OR) to boolean arguments (or types contextually-convertible to bool), with a boolean result. Unlike the bitwise logic operators, these operators (in their built-in form) do not evaluate the second operand if the result is known after evaluating the first.

Builtin operators

The following built-in function signatures participate in overload resolution:

<tbody> </tbody>

bool operator!(bool)

bool operator&&(bool, bool)

bool operator||(bool, bool)

If the operand is not bool, it is converted to bool using contextual conversion to bool: it is only well-formed if the declaration bool t(arg) is well-formed, for some invented temporary t.

For the built-in logical NOT operator, the result is true if the operand is false. Otherwise, the result is false.

For the built-in logical AND operator, the result is true if both operands are true. Otherwise, the result is false. If the first operand is false, the second operand is not evaluated.

For the built-in logical OR operator, the result is true if either the first or the second operand (or both) is true. If the firstoperand is true, the second operand is not evaluated.

Results

a true false
!a false true
and a
true false
b true true false
false false false
or a
true false
b true true true
false true false

Exemplo

#include <iostream>
#include <string>
int main()
{
    int n = 2;
    int* p = &n;
    // pointers are convertible to bool
    if(    p && *p == 2   // "*p" is safe to use after "p &&"
       || !p &&  n != 2 ) // || has lower precedence than &&
        std::cout << "true\n";

    // streams are also convertible to bool
    std::cout << "Enter 'quit' to quit.\n";
    for(std::string line;    std::cout << "> "
                          && std::getline(std::cin, line)
                          && line != "quit"; )
        ;
}

Saída:

true
Enter 'quit' to quit.
> test
> quit

Biblioteca padrão

Because the short-circuiting properties of operator&& and operator|| do not apply to overloads, and because types with boolean semantics are uncommon, only two standard library classes overload these operators:

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)

Verifica se um erro ocorreu (sinônimo de

fail()

)

Original:

checks if an error has occurred (synonym of

fail()

)

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_ios função pública membro) [edit]

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)