C++运算符重载

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

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

38.类和对象-C++运算符重载-加号运算符重载

加号运算符重载
作用:实现两个自定义数据类型相加的运算

#include <iostream>
using namespace std;

// 左移运算符重载
class Person
{
	public:
		//利用成员函数重载 左移运算符 p.operator<<(cout)简化版本p <<cout
		//不会利用成员函数重载 << 运算符,因为无法实现,cout在左侧
		//	void operator<<(cout)
		//	{
		//	}


		int my_a;
		int my_b;

};

//只能利用全局函数重载左移运算符
ostream& operator<<(ostream &cout, Person& p) // 本质 operator<< (cout,p)简化cout<<p
{
	cout << "my_a= " << p.my_a << " my_b" << p.my_b;
	return cout;
}



void test01()
{
	Person p1;
	p1.my_a = 100;
	p1.my_b = 200;
	cout << p1<<endl ;

}


int main()
{
	test01();
	return 0;
}


在这里插入图片描述

39.类和对象-C++运算符重载-左移运算符重载

#include <iostream>
using namespace std;

// 左移运算符重载
class Person
{
	friend ostream& operator<<(ostream& cout, Person& p);

public:
	Person(int a ,int b) {
		my_a = a;
		my_b = b;
	}
	private:
		//利用成员函数重载 左移运算符 p.operator<<(cout)简化版本p <<cout
		//不会利用成员函数重载 << 运算符,因为无法实现,cout在左侧
		//	void operator<<(cout)
		//	{
		//	}


		int my_a;
		int my_b;

};

//只能利用全局函数重载左移运算符
ostream& operator<<(ostream &cout, Person& p) // 本质 operator<< (cout,p)简化cout<<p
{
	cout << "my_a= " << p.my_a << " my_b" << p.my_b;
	return cout;
}



void test01()
{
	Person p1(255,256);
	cout << p1<<endl ;

}


int main()
{
	test01();
	return 0;
}


在这里插入图片描述

40.类和对象-C++运算符重载-递增运算符重载

递增运算符重载
作用:通过重载递增运算符,实现自己的整型数据

在这里插入图片描述

#include <iostream>
using namespace std;
// 重载递增运算符
//自定义整型
class MyInteger
{
friend ostream& operator<<(ostream& cout, MyInteger myint);
private:
	int my_num;
public:
	MyInteger()
	{
		my_num = 0;
	}
	// 重载前置++运算符
	MyInteger& operator++()
	{
		my_num++;
		return *this;
	}

	// 重载后置++运算符
	//void operator++(int) int代表占位参数,可以用于区分前置和后置递增
	MyInteger operator++(int)
	{
		// 先记录当时结果
		MyInteger temp = *this;
		// 后递增
		my_num++;
		// 最后将记录结果做返回
		return temp;

	}

};


// 重载<<运算符
ostream& operator<<(ostream& cout,MyInteger myint)
{
	cout << myint.my_num;
	return cout;
}

void test01()
{
	MyInteger myint;
	cout << ++(++myint) << endl;
	cout << myint << endl;

}

void test02()
{
	MyInteger myint;
	cout << myint++ << endl;
	cout << myint << endl;

}

int main()
{
	test02();
	return 0;
}


41.类和对象-C++运算符重载-赋值运算符重载

C++编译器至少给—个类添加4个函数
1.默认构造函数(无参,函数体为空)
⒉.默认析构函数(无参,函数体为空)
3.默认拷贝构造函数,对属性进行值拷贝
4.赋值运算符operator=,对属性进行值拷贝

如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题

42.类和对象-C++运算符重载-关系运算符重载

43.类和对象-C++运算符重载-函数调用运算符重载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值