单目运算符-作为成员重载

单目运算符-作为成员重载

#include "stdafx.h"
#include <iostream>
using namespace std;

//单目运算符重载
//M# #M ++a a++
//operator#(L); 作友元
//L.operator#(); 作成员


class Complex
{
public:
	Complex(float x = 0, float y = 0)
		:_x(x), _y(y){}
	void dis()
	{
		cout << "(" << _x << "," << _y << ")" << endl;
	}

	//返回类型为const是因为不能修改 例如-n=30; 不能用30将-n的值修改

	//而函数为const函数是因为 负号- 允许再次调用 例如-(-n); 

	//而-n的返回类型为const类型 const类型数据只能调用const类型函数 
	//所以此函数也需要是const类型的

	const Complex operator-() const
	{
		//Complex c;
		//c._x = -this->_x;
		//c._y = -this->_y;
		//return c;

		//Complex c(-this->_x, -this->_y);
		//return c;
		return Complex(-this->_x, -this->_y);//直接返回构造后的对象

	}

private:
	float _x;
	float _y;
};


int _tmain(int argc, _TCHAR* argv[])
{
	int n = 5;
	cout << n << endl;
	cout << -n << endl;
	cout << -(-n) << endl;

	//-n=30;  编译不能通过

	cout << "================================" << endl;

	Complex c(1, 1);

	Complex t = -(-c); // c.operator-().operator-();
	c.dis();
	t.dis();

	Complex m = (2, 2);

	//-c = m;

	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值