为什么我得到的错误与'operator ^'不匹配

时间:2016-10-08 09:58:44

标签: c++ operators xor operator-precedence

我收到错误

10:13: error: no match for 'operator^' (operand types are 'std::basic_ostream<char>' and 'int')
10:13: note: candidates are:
In file included from /usr/include/c++/4.9/ios:42:0,
             from /usr/include/c++/4.9/ostream:38,
             from /usr/include/c++/4.9/iostream:39,
             from 2:
/usr/include/c++/4.9/bits/ios_base.h:161:3: note: std::_Ios_Iostate std::operator^(std::_Ios_Iostate, std::_Ios_Iostate)
operator^(_Ios_Iostate __a, _Ios_Iostate __b)
^

代码是

// Example program
#include <iostream>
#include <string>

int main()
{
int a=1;
int b=2;

std::cout<<a^b;
}

operator ^可以使用哪些操作数?

1 个答案:

答案 0 :(得分:5)

根据Operator Precedenceoperator<<的优先级高于operator^。因此std::cout<<a^b;等同于(std::cout<<a)^b;; (std::cout<<a)将通过引用返回std::cout,这是std::basic_ostream<char>;正如错误消息所述,您无法使用operator^std::cout)和std::basic_ostream<char>致电int

您可以使用括号来指定操作数应如何绑定到运算符的优先级。

std::cout << (a^b);
//           ~   ~