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

运算符重载为友元函数的问题

chen1204019 发布于 2013-06-06 16:50, 624 次点击
#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(double r=0.0, double i=0.0):real(r), imag(i) {}
    friend Complex operator+(const Complex &c1, const Complex &c2);
    friend Complex operator-(const Complex &c1, const Complex &c2);
    friend ostream &operator<<(ostream &out, const Complex &c);
private:
    double real;
    double imag;
};

Complex operator+(const Complex &c1, const Complex &c2)
{
    return Complex(c1.real+c2.real, c1.imag+c2.imag);
}
Complex operator-(const Complex &c1, const Complex &c2)
{
    return Complex(c1.real-c2.real, c1.imag-c2.imag);
}
ostream &operator<<(ostream &out, const Complex &c)
{
    out<<"("<<c.real<<","<<c.imag<<")";
    return out;
}
int main()
{
    Complex c1(5, 4), c2(2, 10), c3;
    cout<<"c1="<<c1<<endl;
    cout<<""c2="<<c2<<endl;
    c3=c1-c2;
    cout<<"c3=c1-c2"<<c3<<endl;
    c3=c1+c2;
    cout<<"c3=c1+c2"<<c3<<endl;
    return 0;
}
为什么运行时会出现错误:fatal error C1001: INTERNAL COMPILER ERROR
怎么回事?
5 回复
#2
zhuxiaoneng2013-06-06 17:00
cout<<""c2="<<c2<<endl;

改为
cout<<"c2="<<c2<<endl;

多了个引号
#3
chen12040192013-06-06 18:06
少了也还是错啊
#4
haoyasen2013-06-06 22:37
我这 没报错阿紫
#5
雪狼633812013-06-06 22:55
重载时,把引用前面的const去掉,因为const表常量
#6
rjsp2013-06-07 08:39
INTERNAL COMPILER ERROR 说的是 编译器出错了,而不是 编译出错了

另外,顺便问一句,例如 friend ostream &operator<<(ostream &out, const Complex &c); 中
为什么将类型 ostream& 要生生的拆成两半,变成了 ostream & ?
为什么将毫无关系的 & 和 out 要生生的绑在一起,变成了 &out?
1