带有std :: ostream运算符的XOR运算符

Tat*_*nho 1 c++ operators xor ostream

我写了一个代表Qubit的课程.因此,对象只有一个值,state,0或1(bool).为了进行必要的计算,我重载了+,*,^等运算符.似乎一切都是正确的+和*,也与^,但只有我不会使用它与std :: ostream运算符.

Qubit x5, x6;
cout << x5^x6; !ERROR!
Run Code Online (Sandbox Code Playgroud)

但随着

Qubit x5, x6;
Qubit z = x5^x6;
cout << z;
Run Code Online (Sandbox Code Playgroud)

它正在工作.我的标准:运营商

std::ostream & operator <<(std::ostream & os, const Qubit & qubit)
{
    os << qubit.GetState();
    return os;
}
Run Code Online (Sandbox Code Playgroud)

和我的XOR操作员

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;
}
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 7

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

由于您没有为a ostream&Qubit(或const Qubit&等)提供过载的XOR运算符,因此编译失败.

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

(注意,+*运算符的优先级高于<<它们描述的工作原理).

最后,你在XOR运算符中有一个严重的内存泄漏(谁会去delete分配的内存?).修复此问题,通过更改函数返回值副本:

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

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