1.基本知识:
- 左值(L-value):左值可以出现在赋值语句的左边或右边;
- 左值(L-value) 的L 应该被理解为Location ,表示可寻址的,有确定地址的
- 右值(R-value): 右值只能出现在赋值语句的右边
- 右值(R-value) 的R 应该被理解为Read ;
- 简单来说, 有确定地址,可取地址的是左值;否则就是右值;
2. C++规定运算符重载必须针对类的对象,即重载时至少有一个参数代表对象(类型如A、const A、A&、const A&、volatile A等) 。
3.C++用operator加运算符进行运算符重载。对于运算符实例成员函数,this隐含参数代表第一个操作数对象;
4.根据能否重载及重载函数的类型,运算符分为:
- 不能重载的:sizeof 、. 、 .* 、 :: 、 ? :
- 只能重载为实例函数成员的:=、–>、( )、[ ]
- 不能重载为实例函数成员的:new、delete
- 其他运算符:都不能重载为静态函数成员,但可以重载为实例函数成员和普通函数(非成员函数)。
class A;
int operator=(int, A&);
A& operator +=(A&,A&);
class A{
friend int operator=(int,A&);
static int operator( )(A&,int);
static int operator+(A&,int);
friend A& operator += (A&,A&);
A& operator ++( );
};
5. 若运算符为传统左值运算符,则重载后运算符函数最好返回非只读有址引用类型(传统左值)。当运算符要求第一个参数为传统左值时,不能使用const说明第一个参数(如this),例如++、–、=、+=等的第一个参数。
6. 若运算结果为传统右值,返回类型最好带有const;
示例代码
class A{
int x, y;
public:
A(int x, int y) { A::x=x; A::y=y; }
A &operator=(const A&m)
{ x=m.x; y=m.y; return *this;};
friend const A operator-(const A&);
friend const A operator+(const A&, const A&);
} a(2,3), b(4,5), c(1, 9);
const A operator -(const A&a){ return A(-a.x, -a.y); }
const A operator +(const A&x, const A&y){
return A(x.x+y.x, x.y+y.y);
}
void main(void){ (c=a+b)=b+b ; c= -b; }
运算符函数的参数
- 重载函数种类不同,参数表列出的参数个数也不同
- 重载为重载为实例成员:参数个数=运算符目数 - 1 (即this指 针)普通函数:参数个数=运算符目数;
- 重载为实例成员:参数个数=运算符目数 - 1 (即this指针);
- 重载为静态成员:参数个数 = 运算符目数(没有this指针);
示例代码
#include <iostream>
using namespace std;
class A
{
int a;
friend A &operator--(A &);
friend A operator--(A &, int);
public:
int get() { return a; }
A &operator++();
A operator++(int);
A(int x) { a = x; }
};
A &operator--(A &x)
{
x.a--;
return x;
}
A operator--(A &x, int)
{
return A(x.a--);
}
A &A::operator++()
{
a++;
return *this;
}
A A::operator++(int)
{
return A(a++);
}
int main()
{
A a(5);
cout << " " << (--a).get() << endl;
cout << " " << (++a).get() << endl;
cout << " " << (a--).get() << endl;
cout << " " << (a++).get() << endl;
return 0;
}
输出
4
5
5
4