第一种就是把运算符重载函数作为类内成员函数,他可以通过this 指针自由的访问本类的数据成员,因此可以少些一个参数
Complex operator +(Complex &);
以下是把运算符重载函数作为类内成员函数 重载‘+’的源代码
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(int ,int );
void set_C(int ,int );
void show_C();
Complex operator +(Complex &);
void set_C(int );//重载函数
private:
int real;
int imag;
};
Complex::Complex(int a=10,int b=10)
{
real=a;
imag=b;
}
void Complex::set_C(int a)
{
real=a;
}
void Complex::set_C(int a,int b)
{
real=a;
imag=b;
}
void Complex::show_C()
{
cout<<real<<'+'<<imag<<'i'<<endl;
}
Complex Complex::operator +(Complex&a2)
{
Complex a1;
a1.real=real+a2.real;
a1.imag=imag+a2.imag;
return a1;
}
int main()
{
Complex C1,C2,C3;
C1.set_C(2,5);
C1.set_C(-2);
C3=C2+C1;
C1.show_C();
C2.show_C();
C3.show_C();
return 0;
}
第二种就是用普通函数重载(注意需要在类内声明为友元函数)
双目运算符重载为友元函数时,由于友元函数不是该类的成员函数,因此在函数的形参列表里必须有两个参数,不能省略
friend Complex operator +(Complex &a1,Complex &a2);//声明为友元函数
以下是用普通函数重载“+”的源代码
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(int ,int );
void set_C(int ,int );
void show_C();
friend Complex operator +(Complex &a1,Complex &a2);//声明为友元函数
void set_C(int );
private:
int real;
int imag;
};
Complex::Complex(int a=10,int b=10)
{
real=a;
imag=b;
}
void Complex::set_C(int a)
{
real=a;
}
void Complex::set_C(int a,int b)
{
real=a;
imag=b;
}
void Complex::show_C()
{
cout<<real<<'+'<<imag<<'i'<<endl;
}
Complex operator +(Complex &a1,Complex&a2)
{
Complex a;
a.real=a1.real+a2.real;
a.imag=a1.imag+a2.imag;
return a;
}
int main()
{
Complex C1,C2,C3;
C1.set_C(2,5);
C1.set_C(-2);
C3=C2+C1;
C1.show_C();
C2.show_C();
C3.show_C();
return 0;
}
1、C++规定,赋值运算符“=”、下标运算符“[ ]”、函数调用运算符"( )"、成员运算符“->”必须作为成员函数重载。
2、流插入“<<”和流提取运算符“>>”、类型转换运算符不能定义为类的成员函数,只能作为友元函数。
3、一般将单目运算符和复合运算符(+=、-=、/=、*=、&=、!=、^=、%=、>>=、<<=)重载为成员函数。
4、一般将双目运算符重载为友元函数。