使用重载操作数" +"内部重载的操作数"<<" C ++中的大小写错误

时间:2018-03-10 17:17:57

标签: c++ overloading operands

首先,我试图在互联网上找到解决方案。在许多教程中我发现了如何重载操作数,但是我发现在另一个重载的操作数中使用了重载的操作数。

我遇到了"<<"和" +",一起使用

我为复数创建结构,由实部和虚部表示。 之后,我创建了重载的操作数" +"它增加了这些结构中的两个,并且运算符"<<&#允许打印此结构。

在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&lt;&lt; L1 + L2;

我做错了什么?

1 个答案:

答案 0 :(得分:0)

你的&lt;&lt;运算符需要声明为:

ostream & operator << (ostream & stream, const Complex & Skl1)