运算符重载就是老出错,看看这程序

来源:百度知道 编辑:UC知道 时间:2024/06/24 08:08:34
#include <iostream>
using namespace std;
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r,double i)
{real=r;imag=i;}
friend Complex operator +(int &i,Complex &c1);
Complex operator +(int &i);
void display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}
private:
double real;
double imag;
};

Complex operator +(int &i,Complex &c1)
{return Complex(i+c1.real,c1.imag);}

Complex::Complex operator +(int &i)
{return Complex(real+i,imag);}
int main()
{Complex c1(5,6),c2;
int i=10;
c2=c1+i;
cout<<"c1=";c1.display();
cout<<"c1+i=";c2.display();
system("pause");
return 0;
}

Complex::Complex operator +(int &i)
{return Complex(real+i,imag);}
上面的函数定义有问题啊。函数的返回值类型要放在前面,可以这样定义:
Complex Complex:: operator +(int &i)
{
return Complex(real+i,imag);
}
这样就没问题了。

system("pause");程序用到这句语句要加头文件
#include<stdlib.h>