这篇记录是在上面原文的基础上加以扩充的,主要因为今天遇到下面两个问题了:
Error:此运算符函数的参数太少
Error:此运算符函数的参数太多
然后在网上看到下面文章,解决了我的问题:
1.运算符重载函数作为类内成员函数
把运算符重载函数作为类内成员函数,它可以通过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;
}
2.运算符重载为友元函数
用普通函数重载(注意需要在类内声明为友元函数)
双目运算符重载为友元函数时,由于友元函数不是该类的成员函数,因此在函数的形参列表里必须有两个参数,不能省略!
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;
}
总结:
- C++规定,赋值运算符“=”、下标运算符“[ ]”、函数调用运算符"( )"、成员运算符“->”必须作为成员函数重载。
- 流插入“<<”和流提取运算符“>>”、类型转换运算符不能定义为类的成员函数,只能作为友元函数。
- 一般将单目运算符和复合运算符(+=、-=、/=、*=、&=、!=、^=、%=、>>=、<<=)重载为成员函数。
- 一般将双目运算符重载为友元函数。