C++ 运算符重载
在 C++ 中,重载是指一个与之前已经在该作用域内声明过的函数或方法具有相同名称的声明, 但是它们的参数列表和定义不相同。C++ 允许在同一作用域中的某个运算符指定多个定义,称为运算符重载。
运算符重载
C++ 使用关键字 operator
重载运算符,并允许重定义或重载大部分 C++ 内置的运算符。重载的运算符是带有特殊名称的函数,函数名是由关键字 operator
和其后要重载的运算符符号构成的。
与其它函数一样,重载运算符有一个返回类型和一个参数列表。例如:
Cube operator+(const Cube&);
重载加法(+
)运算符用于把两个 Cube
对象相加,返回最终的 Cube
对象。
大多数的重载运算符可被定义为普通的非成员函数,或者被定义为类成员函数。如果我们将上面的函数定义为类的非成员函数,那么需要为每次操作传递两个参数。
Cube operator+(const Cube&, const Cube&);
下面通过一个示例加深对运算符重载的理解,在这个示例中,对象作为参数进行传递,对象的属性使用 this
运算符进行访问。
#include <iostream>
using namespace std;
class Cube
{
public:
double getVolume(void)
{
return length * width * height;
}
void setLength( double l )
{
length = l;
}
void setWidth( double w )
{
width = w;
}
void setHeight( double h )
{
height = h;
}
// 重载 + 运算符,用于把两个 Cube 对象相加
Cube operator+(const Cube& b)
{
Cube c;
c.length = this->length + b.length;
c.width = this->width + b.width;
c.height = this->height + b.height;
return c;
}
private:
double length; // 长度
double width; // 宽度
double height; // 高度
};
int main( )
{
Cube c1; // 声明 c1,类型为 Cube
Cube c2; // 声明 c2,类型为 Cube
Cube c3; // 声明 c3,类型为 Cube
double volume = 0.0; // 把体积存储在该变量中
// 设置 c1 属性
c1.setLength(10.0);
c1.setWidth(10.0);
c1.setHeight(10.0);
// 设置 c2 属性
c2.setLength(20.0);
c2.setWidth(20.0);
c2.setHeight(20.0);
// 获取 c1 的体积
volume = c1.getVolume();
cout << "Volume of c1 : " << volume << endl;
// 获取 c2 的体积
volume = c2.getVolume();
cout << "Volume of c2 : " << volume << endl;
// 把两个对象相加,得到 c3
c3 = c1 + c2;
// 获取 c3 的体积
volume = c3.getVolume();
cout << "Volume of c3 : " << volume << endl;
return 0;
}
使用 g++ main.cpp && ./a.out
命令编译运行以上示例,输出结果如下:
Volume of c1 : 1000
Volume of c2 : 8000
Volume of c3 : 27000
运算符符号
可重载运算符
下表列出的是 C++ 中允许重载的运算符。
+ - * / % ^
& | ~ ! , =
< > <= >= ++ --
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []
不可重载运算符
C++ 中不可重载的运算符有四个:::
、.*
、.
、?:
。