首先,我试图在互联网上寻找解决方案。在许多教程中,我找到了如何重载操作数,但我在任何地方都找不到在另一个重载操作数中使用重载操作数。
我对“<<”和“+”一起使用有问题
我为复数创建结构,由实部和虚部表示。 之后,我创建了添加其中两个结构的重载操作数“+”,以及允许打印此结构的运算符“<<”。
在 Visual Studio 上编译时一切正常,但是当我尝试在 linux 上编译它时(命令 g++ -o -pedantic -Wall a.cpp):
#include <iostream>
#include <math.h>
using namespace std;
struct Complex {
double re;
double im;
};
Complex operator + (Complex Skl1, Complex Skl2)
{
Complex result;
result.re = Skl1.re + Skl2.re;
result.im = Skl1.im + Skl2.im;
return result;
}
ostream & operator << (ostream & stream, Complex & Skl1)
{
stream << "(" << Skl1.re << showpos << Skl1.im << noshowpos << "i" << ")";
return stream;
}
int main(){
Complex L1, L2;
L1.re = 1;
L1.im = 2;
L2.re = 3;
L2.im = 4;
cout << L1 + L2;
return 0;
}
我看到这个错误:
a.cpp:31:8: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Complex')
cout << L1 + L2;
我做错了什么?
最佳答案
您的 << 运算符需要声明为:
ostream & operator << (ostream & stream, const Complex & Skl1)
关于c++ - 在 C++ 中使用重载操作数 "+"重载操作数 "<<"大小写错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49211847/