一、运算符重载的概念
1. 支持重载的运算符
// 以下运算符可被重载
+ - * / % ^ & | ~
= < > += -= *= /= %=
^= &= |= << >> >>= <<= ==
!= <= >= ! && || ++ --
, ->* -> () []
new new[]
delete delete[]
// 以下运算符不可被重载
. .* :: ?:
sizeof typeid
static_cast dynamic_cast const_cast reinterpret_cast
2. 运算符重载的规律和限制
- 不能创建新的运算符
- 运算符重载后,操作数的个数不变
- 运算符重载后,运算符的优先级不变
二、运算符重载的形式
1. 以成员函数形式重载运算符
class Integer
{
public:
Integer(int n = 0): i(n) {};
Integer operator+(const Integer& n) const{
return Integer(i + n.i);
}
private:
int i;
}
- 特点:可对第二个变量进行自动类型转换,不对第一个变量进行自动类型转换
Integer x(1), y(5), z;
z = x + y; // 合法
z = x + 3; // 合法,自动由 3 构造 Integer 类的对象
z = 3 + y; // 不合法,3 不会转换为 Integer 类的对象
- 对于二元运算符,重载函数接收一个参数;对于一元运算符,重载函数不接收参数
Integer operator-() const{
return Integer(-i);
}
2. 以全局函数形式重载运算符
class Integer
{
public:
friend Integer operator+(const Integer&, const Integer&);
private:
int i;
};
Integer operator+(const Integer& lhs, const Integer& rhs)
{
return Integer(lhs.i + rhs.i);
}
Integer x(1), y(5), z;
z = x + 3; // 合法,自动由 3 构造 Integer 类的对象
z = 3 + y; // 合法,自动由 3 构造 Integer 类的对象
- 问题:重载函数内部若访问对象的私有字段,需将该重载函数定义为该类的
friend
,或使用权限为 public
的接口