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

Why do i get an error no match for 'operator^'

本文关键字:不匹配 错误 operator 为什么      更新时间:2023-10-16

我得到一个错误

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 ^可以使用哪些操作数

根据运算符优先级,operator<<的优先级高于operator^。所以std::cout<<a^b;(std::cout<<a)^b;是等价的;(std::cout<<a)将通过引用返回std::cout,这是std::basic_ostream<char>;正如错误信息所说,您不能使用std::cout (std::basic_ostream<char>)和int调用operator^

可以使用括号指定操作数与操作符绑定的优先级。

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