我写了一个代表Qubit的类。所以对象只有一个值,状态,0或1(布尔)。为了进行必要的计算,我重载了像+,*,^这样的运算符。 似乎一切都可以用+和*,还有^,但只有当我不会将它与std :: ostream运算符一起使用。使用std :: ostream运算符的XOR运算符
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;
}
和我的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;
}
回到您的C++书籍,并查看有关运算符优先级的章节。 –
http://en.cppreference.com/w/cpp/language/operator_precedence –
你在'operator ^'函数中有内存泄漏。还要详细了解[运算符重载](http://en.cppreference.com/w/cpp/language/operators),特别是规范[二进制算术运算符部分](http://en.cppreference.com/w/cpp /语言/运营商#Binary_arithmetic_operators)。注意这个例子告诉你通过值*返回*而不是通过引用返回。 –