C++ 运算符重载 ++ --

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&);//A*和A[ ]参数不代表对象
class A{
	friend int operator=(int,A&); //错误,不存在operator=
	static int operator( )(A&,int); //错误,不能为静态成员
	static int operator+(A&,int); //错误,不能为静态成员
	friend A& operator += (A&,A&); //正确
	A& operator ++( ); //正确:隐含参数this代表一个对象
};
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); //A(x.x+y.x, x.y+y.y)为类A的常量
}
void main(void){ (c=a+b)=b+b /*c=a+b, c=b+b*/; c= -b; } 
运算符函数的参数
  • 重载函数种类不同,参数表列出的参数个数也不同
    • 重载为重载为实例成员:参数个数=运算符目数 - 1 (即this指 针)普通函数:参数个数=运算符目数;
    • 重载为实例成员:参数个数=运算符目数 - 1 (即this指针);
    • 重载为静态成员:参数个数 = 运算符目数(没有this指针);
示例代码
#include <iostream>
using namespace std;

class A
{
    int a;
    friend A &operator--(A &);//无this,仅一个参数,前置  
    //有多个运算符 "++" 与这些操作数匹配: -- 函数 "operator++(A &)" -- 函数 "A::operator++()" -- 操作数类型为:  ++ A
    friend A operator--(A &, int); //两个参数,后置运算
public:
    int get() { return a; }
    A &operator++();   //只有this参数,前置
    A operator++(int); //包括this共两个参数,后置
    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++()
{//前置 ++ 返回引用对象(左值)
//前置运算结果的左值等于当前对象,且返回的引用对象不能引用局部对象
//故必须return *this 返回对当前对象的引用
    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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值