注册 登录
编程论坛 C++教室

c++形参加引用的问题。

花脸 发布于 2018-01-11 22:25, 1047 次点击

#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')
2 回复
#2
rjsp2018-01-13 09:44
const Complex& c
#3
花脸2018-01-13 20:19
回复 2楼 rjsp
为什么要好这样改?
1