Omk*_*ora 3 c++ operator-overloading
错误如下(倒数第二行):
Error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Complex()')|
Run Code Online (Sandbox Code Playgroud)
这是代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
Complex a();
Run Code Online (Sandbox Code Playgroud)
这是一个令人头疼的解析。您认为它的意思是“默认初始化a具有 type的变量Complex”。但是,编译器将其解析为“声明一个a不带参数并返回Complex值的调用函数”。语法不明确:它可能意味着两者之一,但语言更喜欢函数声明而不是变量声明。
因此,a是一个函数,而不是一个变量。
事实上,没有声明的运算符重载接受一个函数,这就是你得到错误的原因。请注意错误中调用的特定类型:
operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Complex()'
parens indicate a function ^^
Run Code Online (Sandbox Code Playgroud)
要解决此问题,请将此行替换为以下之一:
Complex a{}; // C++11 and later only; uniform initialization syntax
Complex a; // All versions of C++
Run Code Online (Sandbox Code Playgroud)
这些都不是模棱两可的。它们只能被解析为变量声明。