“+”号是双目运算符,但是为什么我们没有重载函数上设为两个参数?其实实际上,运算符重载函数有两个参数,由于重载函数是Complex类中的成员函数,有一个参数是隐含的运算符函数是用this指针隐式地访问类对象的成员。
程序二是“运算符重载函数作为类成员函数和有友元函数”,在这里我们就要显式使用两个参数了
//
程序一:
#include<iostream>
using namespace std ;
class Complex{
public :
Complex (){real =0 ; imag =0 ;}
Complex (double r, double i ){real =r ; imag = i ;}
Complex operator + (Complex &c2){
real = real +c2.real ;
imag = imag + c2 .imag;
return *this ;
};
void display();
private :
double real;
double imag;
};
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int main()
{
Complex c1(3,4),c2(5,-10),c3;
c3= c1+c2 ;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
cout<<"c1+c2=";
c3.display();
return 0 ;
}
//
程序二:
#include<iostream.h>
//using namespace std;class Complex //复数类
{
private:
double image;
double real;
public:
Complex(double x=0.0,double y=0.0)//构造函数
{
real =x; image =y;
}
void Print();
friend Complex operator +(const Complex &c1,const Complex &c2);
};
void Complex::Print()
{
cout<<real<<"+"<<image<<"i"<<endl; //以复数格式输出
}
Complex operator +( const Complex &c1, const Complex &c2)
{
Complex temp(c1.real+c2.real,c1.image+c2.image);
return temp;
}
int main()
{
Complex c1(2,7),c2(4,2),c3;
c3=c1+c2; //表达式的完整形式应该是 c3=operator+(c1,c2)
c3.Print();
return 0;
}