【发布时间】:2018-03-10 17:17:56
【问题描述】:
首先,我试图在互联网上找到解决方案。在许多教程中,我发现了如何重载操作数,但在任何地方我都没有发现在另一个重载操作数中使用重载操作数。
我对“
我为复数创建结构,由实部和虚部表示。 之后,我创建了重载操作数“+”,它添加了其中两个结构,以及运算符“
在 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
我做错了什么?
【问题讨论】:
-
代码在哪里?
-
不,C++ 通常不禁止组合两个独立的功能或两个独立的功能使用。按理说返回的对象玩得不好。也许您的
operator<<过载需要Complex&。您需要发布minimal reproducible example 以便任何人确定。 -
您可能希望为
Complex&&重载std::ostream& operator<< -
发布minimal example。您发布的错误可能只是错误代码的一部分,周围的行将包含更多详细信息
-
感谢克里斯的链接,我已经更正了帖子。
标签: c++ overloading operands