c++ - XOR 运算符与 std::ostream 运算符

标签 c++ operators xor ostream

我写了一个代表 Qubit 的类。所以对象只有一个值,state,有 0 或 1 (bool)。为了进行所需的计算,我重载了 +、*、^ 等运算符。 看起来 + 和 * 一切正常,^ 也是如此,但前提是我不会将它与 std::ostream 运算符一起使用。

Qubit x5, x6;
cout << x5^x6; !ERROR!

但与

Qubit x5, x6;
Qubit z = x5^x6;
cout << z;

它正在工作。我的标准:运算符

std::ostream & operator <<(std::ostream & os, const Qubit & qubit)
{
    os << qubit.GetState();
    return os;
}

和我的异或运算符

Qubit & Qubit::operator ^(const Qubit & qubit)
{
    Qubit *q = new Qubit;
    ((this->state == 1 && qubit.state == 0) ||
        (this->state == 0 && qubit.state == 1)) ? q->SetState(1) : q->SetState(0);
    return *q;
}

最佳答案

cout << x5 ^ x6被评估为 (cout << x5) ^ x6由于运算符优先级

因为您没有为 ostream& 提供重载的 XOR 运算符和一个 Qubit (或 const Qubit& 等),编译失败。

解决方案是写cout << (x5 ^ x6);

(请注意,+* 运算符的优先级高于 <<,这就是它们按您描述的方式工作的原因)。

最后,异或运算符中存在严重的内存泄漏(谁去 delete 分配的内存?)。通过更改函数以返回值拷贝来解决此问题:

Qubit Qubit::operator^(const Qubit& qubit) const

并使用Qubit q;在函数体内。 命名返回值优化将避免值复制。有关详细信息,请参阅 http://en.cppreference.com/w/cpp/language/operator_arithmetic

关于c++ - XOR 运算符与 std::ostream 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40865102/

相关文章:

c++ - 如何编写带有 'asm volatile'的btr指令

c++ - 在 C++ 中使用 CLists - 无法理解

c++ - STL - 赋值运算符与 `assign` 成员函数

Python等于运算符,避免: (<string> == <number>) -> False类型的bug

c++ - 最小异或值 : Given an integer array A of N integers, 找出数组中具有最小异或值的整数对

api - Swagger API 文档 XOR

c++ - 为什么具有虚函数的类与没有虚函数的类对齐方式不同?

c++ - 在本地使用 reference_wrapper 初始化 vector

java - Java中=+运算符的使用?

java - Java 中与负字节的异或