类和对象————运算符重载

对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

.1加号运算符重载

实现自定义数据类型相加。

  1. 成员函数实现
  2. 全局函数实现
class Person {

public:
	int m_a;
	int m_b;

	//1.全局函数实现
	//Person operator+(Person& p) {
	//	Person temp;
	//	temp.m_a = this->m_a + p.m_a;
	//	temp.m_b = this->m_b + p.m_b;
	//	return temp;
	//}

};

//2.全局函数实现
Person operator+(Person& p1, Person& p2) {
	Person temp;
	temp.m_a = p1.m_a + p2.m_a;
	temp.m_b = p1.m_b + p2.m_b;
	return temp;
}

//调用
void test() {
	Person p1;
	Person p2;
	p1.m_a = 2;
	p1.m_b = 5;
	p2.m_a = 5;
	p2.m_b = 2;

	//成员函数重载本质调用
	Person p3 = p1.operator+(p2);

	//全局函数重载本质调用
	Person p3 = operator+(p1, p2);

	//简化形式
	Person p3 = p1 + p2;

	cout << p3.m_a << endl;

	cout << p3.m_b << endl;
}

.2左移运算符重载 <<

输出自定义类型。只能利用全局函数重载,因为成员函数重载void operator<<(ostream &cout) {}会使得输出语法变为p<<cout;

//全局函数实现
ostream & operator<<(ostream &cout, Person &p) {		//调用本质是 operator<<(cout,p)
	cout << p.m_a << endl;								//简化后  cout <<p;
	cout << p.m_b << endl;
	return cout;			//链式编程思想,可使<<后继续输出
}

可配合友元输出自定义类型

.3递增运算符重载

重载前置++运算符
同样Person &的返回类型为了链式编程 如++(++p) ,一直对p进行递增操作,而不是创建副本

Person & operator++() {			
	p.m_a++;
	p.m_b++;
	return p;
}

重置后置++运算符,只能成员函数实现

Person operator++(int) {		//返回的是值,且用int 作为占位参数与前置++区分
	Person temp = *this;		//先返回
	m_a++;						//再递增
	m_b++;
	return temp;			
}

.4赋值运算符重载

编译器自动会提供一个函数 operator= ,但对于堆区的属性会出现深浅拷贝问题,造成重复释放。
.5深拷贝与浅拷贝

class Person {

public:
	int* m_age;

	Person(int age) {
		m_age = new int (age);			//堆区开辟内存
	}
		
	Person& operator=(Person &p) {
		if (m_age != NULL) {			//拷贝前先判断堆区是否有属性,如果有先释放干净
			delete m_age;
			m_age = NULL;
		}
		
		m_age = new int(*p.m_age);		//深拷贝

		return *this;					//返回对象本身
	}

	~Person() {
		if (m_age != NULL) {
			delete m_age;				//堆区释放内存
			m_age = NULL;
		}
 	}
};

void test() {
	Person p1(10);
	Person p2(20);
	Person p3(2);
	p2 = p1=p3;							//赋值
	cout <<* p1.m_age << endl;
	cout << *p2.m_age << endl;
	cout << *p3.m_age << endl;
}

.5关系运算符重载

==与!=关系判断

bool operator==(Person& p) {
	if (判断条件) {
		return true;
	}
	return false;
}
	

.6函数调用运算符重载

仿函数:自己实现一种函数类

//自定义输出类
class MyPrint {
public:
	void operator()(string name) {
		cout << name << endl;
	}
};

void test() {
	MyPrint p;
	p("hello");
}

匿名对象调用

class MyAdd {
public:
	int operator()(int a,int b) {
		return a + b;
	}
};

void test() {
	MyAdd add;
	int ret = add(1, 1);
	//匿名对象调用
	cout << MyAdd()(1, 1) << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值