一.
1.函数重载的概念:对一个已有的函数赋予新含义。
2.运算符重载的一般形式:函数类型 operator 运算符名称(形参表列){运算符重载函数体}。
3.重载运算符函数的函数名为 数据类型名 operator。
4.对于同一运算符,编译系统是根据操作对象两侧的数据类型(如果是单目运算符则为一侧)来决定要编译的函数的。
5.重载运算符的几个规则:(1)不能改变操作数个数(2)不能改变优先级(3)不能改变结合性(4)不能有默认的参数。(5)用于类对象的运算符一般必须重载。
6.代码示例如下(选自c++程序设计 谭浩强版)
#include<iostream>
using namespace std;
class Complex
{
public:
Complex() { real = 0; imag = 0; };//定义无参构造函数
Complex(double i, double j) { real = i; imag = j; };//定义有参构造函数
Complex operator + (Complex &a);//声明 一个重载运算符函数
void display();
private:
double real;
double imag;
};
Complex Complex::operator + (Complex &a)//定义一个重载运算符函数
{
// 1 Complex b;
/*b.real = real + a.real;
b.imag = imag + a.imag;
return b;*/
return Complex(real + a.real, imag + a.imag);//也可以通过此方式实现,建立一个临时对象,此对象无名
}
void Complex::display()
{
cout << "(" << real << "," << imag<<"i" << ")" << endl;
}
int main()
{
Complex c1(3, 1);
Complex c2(3, 4);
Complex c3;
//c3 = c1 + c2;
c3 = Complex(3,1) +c2;
cout << "c1="; c1.display();
cout << "c2="; c2.display();
cout << "c1+c2=";c3.display();
return 0;
}
7.上面的c1+c2相当于 c1.operator+c2.
二.运算符重载函数作为友元函数。
代码示例如下:
#include<iostream>
using namespace std;
class Complex
{
public:
Complex() { real = 0; imag = 0; };//定义无参构造函数
Complex(double i, double j) { real = i; imag = j; };//定义有参构造函数
friend Complex operator + (Complex &a ,Complex &b);//声明 一个友元重载运算符函数
void display();
private:
double real;
double imag;
};
Complex operator + (Complex &a,Complex &b)//定义一个普通类重载运算符函数
{
return Complex(b.real + a.real, b.imag+ a.imag);//也可以通过此方式实现,建立一个临时对象,此对象无名
}
void Complex::display()
{
cout << "(" << real << "," << imag<<"i" << ")" << endl;
}
int main()
{
Complex c1(3, 1);
Complex c2(3, 4);
Complex c3;
c3 = c1 + c2;
cout << "c1="; c1.display();
cout << "c2="; c2.display();
cout << "c1+c2=";c3.display();
return 0;
}
1.将双目运算符重载为友元函数时,由于友元函数不是该类的成员函数,因为函数的形参表列中必须有两个参数。
2.运算符要对应于它相应的操作数。