c++形参加引用的问题。
#include <iostream>
#include <string>
using namespace std;
//复数类
class Complex{
private:
float a; //复数实部
float b; //复数虚部
public:
Complex(float fa, float fb=0) :a(fa), b(fb){}
Complex operator+(Complex c) ;//重载加法
friend ostream& operator<<(ostream& out,Complex &c);//这样报错。但是Complex c这样就不错了,这是为什么。
};
Complex Complex::operator+(Complex c)
{
c.a += a;
c.b += b;
return c;
}
ostream& operator<<(ostream& out, Complex &c)//
{
if (c.b != 0)
out << c.a << "+" << c.b << "i";
else
out << c.a;
return out;
}
int main()
{
Complex c1(2, 3);
Complex c2(3);
cout << c1 + c2 << endl;
return 0;
}
错误信息。
[Error] no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Complex')