c++学习心得一元运算符重载

学了c,c++,算是基本入门了吧,以前做的好多笔记由于硬盘坏了,换了硬盘后数据都丢了,只好从c++模版篇开始了,写博客呢不仅可以加深自己的印象,更好的复习学过的知识,也有助于对知识的总结,归纳,写得不好,还请高人指点指点。好了,步入正题吧, c++中可以用直接用"+"实现字符串的连接,比如string a="hello",cout<<a+" world"<<endl;(补充一句,直接定义string a="hello "+"world"这样是错误的) 这就是运算符重载(本质就是函数重载,关键字operator),类中分为友元函数重载和成员函数重载,以简单的坐标类为例把,写法

class Coordinate{
              friend Coordinate &opetator-(coordinate &coor){//需要传入参数(前置)
                   coor.m_iX=-coor.m_iX;   
                    coor.m_iY=-coot.m_iY;
                    return *this;
                    }
             friend Coordinate operator++(Coordinate& c,int){//后置的话operator前不加引用
                    Coordinate c1(c);
                    c.m_iX++;
                   c.m_iY++;
                   return c1;
               }


# include <iostream>
using namespace std;
class Coordinate{
	friend Coordinate& operator++(Coordinate &coor)//友元函数重载(全局)operator前不加引用
	{
		++coor.m_iX;
		++coor.m_iY;
		return coor;
	}

public:
	Coordinate(int x, int y){
	
		m_iX = x;
		m_iY = y;
	}
	int getX(){
		return m_iX;
	}
	int getY(){
		return m_iY;
	}
	
	  
		
	Coordinate &operator-(){   //成员函数重载
		m_iX = -m_iX;
		m_iY = -m_iY;
		return *this;
	}

private:
	int m_iX;
	int m_iY;

};

int main(){

	Coordinate c1(1,1);
	-c1;
	cout << c1.getX() << " " << c1.getY() << endl;
	++c1;
	cout << c1.getX() << " " << c1.getY() << endl;

	system("pause");
	return 0;
}


转载于:https://my.oschina.net/mylanbo/blog/664868

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值