重载
c++允许某个函数、运算符 指定多个定义或者不同参数。
即他们的函数/运算符名一样,但是参数列表和具体实现不一样。
函数的重载比较常见,这里我们看以下运算符的重载。
运算符重载
使用方法以两个对象作用为例:
类的成员函数:
Box operator运算符(const Box&);
非成员函数:
Box operator+(const Box&, const Box&);
下面的实例使用成员函数演示了运算符重载的概念。在这里,对象作为参数进行传递,对象的属性使用 this 运算符进行访问,如下 Box operator+(const Box& b)函数所示:
该函数返回一个box类型的对象,这个对象在函数内被构造,参数由调用对象this和被加对象b各属性相加得到
#include <iostream>
using namespace std;
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
// 重载 + 运算符,用于把两个 Box 对象相加
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // 长度
double breadth; // 宽度
double height; // 高度
};
// 程序的主函数
int main( )
{
Box Box1; // 声明 Box1,类型为 Box
Box Box2; // 声明 Box2,类型为 Box
Box Box3; // 声明 Box3,类型为 Box
double volume = 0.0; // 把体积存储在该变量中
// Box1 详述
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// Box2 详述
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// Box1 的体积
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// Box2 的体积
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// 把两个对象相加,得到 Box3
Box3 = Box1 + Box2;
// Box3 的体积
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
可/不可重载的运算符例举
下列运算符可重载:
下列不可重载:
一元运算符重载
主要包括
- 递增++递减–
- 负号-
- 非!
假设有构造函数,其中distance是一个类
Distance(int f, int i){
feet = f;
inches = i;
}
我们可以重载负号-:
Distance operator-()
{
Distance d;
d.feet=-feet;
d.inches=-inches;
return d;
}
这样我们在使用时可以这样
Distance D1(1,2),D2;
D2=-D1;
二元运算符重载
我们举例的时候举的加号+就是二元运算符。注意传参的时候最好使用
box operater+(const box &x)
用const 表示x 这个box的值不会被改变。
输入输出运算符重载
这个主要是我们可以重载输出符,方便输出一个自己想要的结果
比如我们可以定义输出一个类:
ostream &operater(ostream & output,const Distance &d)
{
output<<"说明"<<d.feet<<" 说明2"<<d.inches;
return output;
}
istream &operator>>( istream &input, Distance &D )
{
input >> D.feet >> D.inches;
return input;
}
自加自减运算符重载(注意体会前缀和后缀区别)
假设有Time类
class Time
{
private:
int hours; // 0 到 23
int minutes; // 0 到 59
public:
// 所需的构造函数
Time(){
hours = 0;
minutes = 0;
}
Time(int h, int m){
hours = h;
minutes = m;
}
}
我们重载前缀++,前缀直接处理该值,返回新值,不保存原来内容(函数参数中不写默认前缀):
Time operater++()
{
++minutes;
if(minutes>=60)
{
++hours;
minutes-=60;
}
return Time(hours,minutes);
}
而后缀++需要保存原始值,且返回的是原始值(注意括号中插入 int 表示后缀):
Time operater(int)// 括号中插入 int 表示后缀
{
Time temp(hours,minutes);
++minutes;
if(minutes>=60)
{
++hours;
minutes-=60;
}
return temp;
}
这里可以参考我之前一篇关于for循环中到底写++i 还是i++的文章:
添加链接描述