C++ 运算符重载

运算符重载使得用户自定义的数据以一种更简洁的方式工作。

让自定义数据类型有机会进行运算符操作 ----------运算符重载机制

运算符重载本质是一种函数,还是调用函数

 

 

运算符重载的规则

(1)不能发明新的运算符

(2)不能改变运算符的操作对象个数

(3)运算符重载后 其优先性和结合性不会变

(4)不能重载的运算符

                作用域解析运算符 ::

                条件运算符 ?:

                直接成员访问运算符 .

                类成员指针引用的运算符 .*

                还有一个 sizeof

(5)除了流运算符是由友元函数重载,其他的运算法最好在类的成员函数中使用

 

运算符重载的格式

函数返回类型 operator 运算符 (参数表);

 

实现运算符重载的两种方法

(1)类的成员函数

(2)友元函数

注意: 成员函数有this指针,友元函数没有this指针

 

 

 

 

成员函数运算符重载

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class Test
{
public:
	Test() {}
	Test(int a, int b)
	{
		this->a = a;
		this->b = b;
	}
	void GET()
	{
		cout << "==============" << endl;
		cout << "a = " << a << endl;
		cout << "b = " << b << endl;
		cout << "==============" << endl;
	}


	//实现二元运算符重载
	//成员函数重载时,函数的参数列表只需要一个形参即可
	//另一个参数是类的成员变量,用this指针表示
	Test operator+(Test &obj)
	{
		Test tmp;
		tmp.a = this->a + obj.a; //使用的使用两个元都在
		tmp.b = this->b + obj.b;
		return tmp;
	}

    //https://www.cnblogs.com/cthon/p/9185263.html    前置++ 和 后置++

	Test& operator++() //前置++     
	{
		++a;
		++b;
		return *this;
	}

	const Test operator++(int) //后置++     
	{
		Test tmp = *this;
		++(*this);  //利用前置++     
		return tmp;
	}


	//重载等号操作符  其实这个是比较常用的  
	//重载=运算符  =运算符应该有两个操作数的 this是一个 t是一个
	Test& operator=(Test & t)
	{
		this->a = t.a;
		this->b = t.b;
		return *this;            //注意返回值
	}

	Test & operator*(int n)
	{
		this->a *= n;
		this->b *= n;
		return *this;
	}

private:
	int a;
	int b;
};

int main()
{
	Test t(3, 4);

	t.GET();

	t = t * 10;

	t.GET();

	t++;

	t.GET();

	++t;

	t.GET();

	return 0;

}

 

用友元函数重载<< >>运算符

//注意 <<  >>  运算符是二元操作符    比如 cout <<  a   cout和a是操作数 

#include <iostream>
using namespace std;
class Test
{
    public:
    	Test(int m,int n):a(m),b(n)
    	{
    	}
    friend ostream& operator<<(ostream &out,Test&tmp);
    private:
    	int a;
    	int b;
};

//友元函数
//函数有返回值可以实现链式编程
/*为什么要有返回值呢   
  void operator<<(ostream &out,Test &tmp)不可以吗  
  其实也是可以的,只不过不能实现链式编程了  cout << t1 <<"12345";   
  当函数没有返回值  执行完cout << t1 后返回的是 void  但是 void.operator<<("12345") 是错误的
  应该是 ostream.operator<<("12345")才可以 ,所以应该返回 ostream*/
ostream & operator<<(ostream &out,Test &tmp) 
{
	out<<tmp.a<<endl;
	out<<tmp.b<<endl;
	return out;
}

int main()
{
	Test t1(1,2);
	cout<<"hello world"<<endl;
	cout<<t1<<endl;
	return 0;
}



 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值