运算符重载
一. 运算符重载概述
~~~~~~ 运算符重载是面向对象程序设计的重要特性。运算符重载是对已有的运算符赋予多重含义,使同一个运算符作用于不同数据类型的数据导致不同的行为。C++为运算符的重载提供了一种方法,即在进行运算符重载时,必须写一个运算符函数,其名规定为operator后随一个要重载的运算符。例如:
函数 | 功能 |
---|---|
operator+() | 加法 |
operator-() | 减法 |
operator*() | 乘法 |
operator/() | 除法 |
operator<() | 小于 |
… | … |
二. 运算符函数重载为类的友元函数和成员函数
1. 友元运算符重载函数
a. 友元运算符重载函数定义的语法形式
// 友元运算符重载函数的原型在类的内部声明的格式如下:
class X
{
...
friend 返回类型 operator 运算符 (形参表);
...
}
// 在类外定义友元函数重载函数的格式如下:
返回类型 operator 运算符(形参表);
{
函数体
}
注意:友元运算符函数没有this指针,若友元运算符重载函数重载的是双目运算符,则参数表中有两个操作符;若重载的是单目运算符,则参数表中只有一个操作数。
b. 双目友元运算符重载函数
c. 单目友元运算符重载函数
2. 成员运算符重载函数
a. 成员运算符重载函数定义的语法形式
// 在类的内部,定义成员运算符重载函数的格式如下
返回类型 operator 运算符 (形参表)
{
函数体
}
// 也可在类中声明成员函数的原型,在类外定义。
【例子】
#include<iostream>
using namespace std;
class Coord
{
private:
int x, y;
public:
Coord(int i=0, int j=0);
void display();
friend Coord operator++(Coord &op);
};
Coord::Coord(int i, int j)
{
x = i;
y = j;
}
void Coord::display()
{
cout << "x: " << x << ",y: " << y << endl;
}
Coord operator++(Coord &op)
{
++ op.x;
++ op.y;
return op;
}
int main()
{
Coord ob(11, 22);
ob.display();
++ob;
ob.display();
++ob;
ob.display();
++ob;
ob.display();
++ob;
ob.display();
return 0;
}