运算符重载
基本概念
重载运算符本质上就是将原有的运算符的功能加以扩充,以达到使程序更加简便的目的。
重载运算符的函数
TYPE operator@(形参表) {
//重新定义运算符@的功能
}
operator是关键字。
• @是要被重载的运算符。
• operator@共同组成该运算符函数的名称。
• TYPE是该运算符函数的返回值类型。
eg:
class Complex
{
public:
double r; //实部
double i; //虚部
}
Complex operator+(Complex &c1, Complex &c2)
{
Complex t;
t.r = c1.r + c2.r;
t.i = c1.i + c2.i;
return t;
}
int main()
{
Complex a(3.0, 4.0), b(10.5, 20.5), c;
c = a + b;
cout<<“c: "; c.Print();
}
重载的两种方式:重载为成员函数,重载为友元函数
重载为成员函数
#include <iostream.h>//成员函数
class Complex
{
private:
double r; //实部
double i; //虚部
public:
Complex operator+(const Complex &c);
Complex operator+(double d);
……
};
Complex Complex::operator+(const Complex &c)
{
Complex t;
t.r = r + c.r;
t.i = i + c.i;
return t;
}
Complex Complex::operator+(double d)
{
Complex t;
t.r = r + d;
t.i = i;
return t;
}
int main()
{
Complex a(3.0, 4.0), b(10.5, 20.5), c, d, e;
c = a.Add(b);
d = a + b;
e = a + 10.5;
d = a.operator +(b);
e = a.operator +(10.5);
c.Print();
d.Print();
e.Print();
}
重载为友元函数
friend TYPE operator@(形参表);
双目运算符,形参中有两个参数;单目运算符,形参中有一个参数。
eg:
class Complex
{
public:
friend Complex operator+(double d, const Complex &c);
……
};
Complex operator+(double d, const Complex &c)
{
Complex t;
t.r = d + c.r;
t.i = c.i;
return t;
}
void main()
{
Complex a(3.0, 4.0), b(10.5, 20.5), c, d, e;
e = 10.5 + a;
……
}
重载规则
不能定义新的运算符。
. .* :: ? sizeof 不能重载
当重载为类的成员函数时,运算符重载函数的形参个数要比运算符操作数个数少一个;若重
载为友元函数,则参数个数与操作数个数相同。
“=”、“()”、“[ ]”、“->”只能通过成员函数重载。
不同类型数据件的类型转换
如果想实现自定义类型数据间的类型转换,可以使用转换构成函数,或者运算符重载。
转换构造函数
class Complex
{
private:
double r;
double i;
public:
Complex() { r = i = 0.0; }
Complex(double d) { r = d; i = 0.0;}
//Complex(double d1, double d2=0.0) { r = d1; i = d2; } //也可以
friend Complex operator+(Complex c1, Complex c2);
};
Complex operator+(Complex c1, Complex c2)
{
return Complex(c1.r+c2.r, c1.i+c2.i);
}
void main()
{
Complex c1 = Complex(1.2);
c1 = Complex(1.2);
Complex c2=5.6;
c2 = 5.6;
Complex c3;
c3 = c1 + 5.6;
c3 = c1 + Complex(5.6);
c3 = c1 + (Complex)5.6;
}