简体   繁体   English

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

[英]XOR operator with std::ostream operator

I wrote a class which represent Qubit. 我写了一个代表Qubit的类。 So object has only one value, state, with 0 or 1 (bool). 因此,对象只有一个值为0或1(布尔)的状态。 To make needed calculations I overloaded operators like +,*,^. 为了进行所需的计算,我重载了+,*,^之类的运算符。 It seems that everything is ok with + and *, also with ^, but only if I won't use it with std::ostream operator. 似乎+和*以及^都可以,但前提是我不会在std :: ostream运算符中使用它。

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

but with 但随着

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

it's working. 它正在工作。 My std:operator 我的std:operator

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

and my XOR operator 和我的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;
}

cout << x5 ^ x6 is evaluated as (cout << x5) ^ x6 due to operator precedence . 由于运算符优先级, cout << x5 ^ x6被评估为(cout << x5) ^ x6

Since you have not provided an overloaded XOR operator for an ostream& and a Qubit (or const Qubit& etc.), compilation fails. 由于尚未为ostream&Qubit (或const Qubit&等)提供重载的XOR运算符,因此编译失败。

The solution is to write cout << (x5 ^ x6); 解决的办法是写cout << (x5 ^ x6);

(Note that the + and * operators have higher precedence than << which is why they work as you describe). (请注意, +*运算符的优先级高于<< ,这就是它们如您所描述的工作原理)。

Finally, you have a serious memory leak in the XOR operator (who is going to delete the allocated memory?). 最后,您在XOR运算符中有严重的内存泄漏(谁将delete分配的内存?)。 Fix that by changing the function to return a value copy: 通过更改函数以返回值副本来解决此问题:

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

and use Qubit q; 并使用Qubit q; in the function body. 在功能体内。 Named Return Value Optimisation will obviate a value copy. 命名为返回值优化将消除值副本。 For more details, see http://en.cppreference.com/w/cpp/language/operator_arithmetic 有关更多详细信息,请参见http://en.cppreference.com/w/cpp/language/operator_arithmetic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM