问题描述
错误看起来像这样(第二行):
Error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Complex()')|
代码如下:
#include <iostream>
using namespace std;
class Complex {
private:
int a,b;
public:
Complex(int x,int y) {
a = x;
b = y;
}
Complex() {
a = 0;
b = 0;
}
friend ostream& operator << (ostream &dout,Complex &a);
friend istream& operator >> (istream &din,Complex &a);
};
ostream& operator << (ostream &dout,Complex &a) {
dout << a.a << " + i" << a.b;
return (dout);
}
istream& operator >> (istream &din,Complex &b) {
din >> b.a >> b.b;
return (din);
}
int main() {
Complex a();
cin >> a;
cout << a;
}
解决方法
Complex a();
这是vexing parse。您认为这意味着“默认初始化变量a
,其类型为Complex
”。但是,编译器将其解析为“声明一个名为a
的函数,该函数不带任何参数并返回一个Complex
值。”语法是模棱两可的:可能有两种含义,但该语言更喜欢函数声明而不是变量声明。
因此,a
是一个函数,而不是变量。
实际上,没有声明的运算符重载采用函数,这就是为什么会出现错误。请注意错误中指出的特定类型:
operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Complex()'
parens indicate a function ^^
要解决此问题,请用以下其中一项替换此行:
Complex a{}; // C++11 and later only; uniform initialization syntax
Complex a; // All versions of C++
这些都不是模棱两可的。它们只能解析为变量声明。