C++学习笔记之运算符重载
首先要明白为什么要重载运算符,其意义何在:
1)我们知道C++的基本数据类型,比如int,都支持 “+ ” “-” “ *” “ /” 操作,但是对于我们自定义的类型(类)的对象,并不支持这些运算符操作,重载运算符就是为了让我们自定义的类型的对象间也支持这些运算符操作。
2)C++不允许程序员自定义新的运算符,所以只能对已有的运算符进行重载。
重载运算符要遵循的一些原则:
1)不支持重载的运算符有5个:成员访问运算符. 作用域运算符:: 条件运算符?: 成员指针运算符* 预处理符号#
2)重载不能改变运算符运算对象的个数,比如重载+运算,参与运算的对象必须为2个
3)重载不能改变运算符的优先级别
4)重载运算符的函数不能有默认的参数,否则就违背了原则2),等于改变了运算符运算对象的个数
5)重载的运算符必须和类的对象一起使用,其参数至少应该有一个是类的对象
运算符重载的格式:
运算符重载其实就是函数的重载
函数类型 operator 运算符名称(形参)
{
对运算符的重载处理
}
举例:
1)一元运算符(-负号)重载
class Distance
{
private:
int feet;
int inches;
public:
Distance()
{
feet = 0;
inches = 0;
}
Distance(int f,int in)
{
feet = f;
inches = in;
}
Distance operator -()
{
feet = -feet;
inches = -inches;
return Distance(feet,inches);
}
};
2)二元运算符重载
class Box
{
private:
int length;
int height;
int breadth;
public:
Box()
{
length = 0;
height = 0;
breadth = 0;
}
Box operator + (const Box &other)
{
Box box;
box.length = this->length + other.length;
box.height = this->height + other.height;
box.breadth = this->breadth + other.breadth;
return box;
}
};
3)下标运算符[]重载
const int SIZE = 10;
class TestArray
{
private:
int arr[SIZE];
public:
TestArray()
{
for(int i=0;i<10;i++)
{
arr[i] = i;
}
}
int& operator [](int i)
{
if(i>SIZE)
{
cout<<"索引超出范围"<<endl;
return arr[0];
}
else
{
return arr[i];
}
}
};

浙公网安备 33010602011771号