运算符重载

所谓重载,就是重新赋予新的含义。函数重载就是对一个已有的函数赋予新的含义,使之实现新功能,因此,一个函数名就可以用来代表不同功能的函数,也就是”一名多用”。

为什么要用运算符重载

1为什么会用运算符重载机制
      用复数类举例
      Complex c3 = c1 + c2;

       复数相加,(1+2i)+(3+4i),编译器不知道(1+2)+(2+4)i
     原因 Complex是用户自定义类型,编译器根本不知道如何进行加减
      编译器给提供了一种机制,让用户自己去完成,自定义类型的加减操作。。。。。
      这个机制就是运算符重载机制
2 运算符重载的本质是一个函数

不能重载的运算符 

  1. ::
  2. .
  3. .*
  4. ?:
  5. sizeof

几个例子:对==和!=的重载

#include<iostream>
using namespace std;
class Complex
{
private:
	int m_a;
	int m_b;
public:
	Complex();
	Complex(int a,int b);
	bool operator==(Complex &c);
	bool operator!=(Complex &c);
};

Complex::Complex()
{
	m_a=0;
	m_b=0;
}

Complex::Complex(int a,int b)
{
	m_a=a;
	m_b=b;
}

bool Complex::operator==(Complex &c)
{
	if(this->m_a==c.m_a && this->m_b==c.m_b)
	{
		return true;
	}
	else
	{
		
		return false;
	}
}

bool Complex::operator!=(Complex &c)
{
	if(this->m_a!=c.m_a || this->m_b!=c.m_b)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main()
{
	Complex c1(1,2);
	Complex c2(2,3);
	if(c1==c2)
	{
		cout<<"相等"<<endl;
	}
	else
	{
		cout<<"不相等"<<endl;
	}
	if(c1 != c2)
	{
		cout<<"不相等"<<endl;
	}
	else
	{
		cout<<"相等"<<endl;
	}
	
	return 0;
}

前置和后置运算符:

#include<iostream>
using namespace std;
class Complex
{
private:
	int m_a;
	int m_b;
public:
	Complex();
	Complex(int a,int b);
	bool operator==(Complex &c);
	bool operator!=(Complex &c);
};

Complex::Complex()
{
	m_a=0;
	m_b=0;
}

Complex::Complex(int a,int b)
{
	m_a=a;
	m_b=b;
}

bool Complex::operator==(Complex &c)
{
	if(this->m_a==c.m_a && this->m_b==c.m_b)
	{
		return true;
	}
	else
	{
		
		return false;
	}
}

bool Complex::operator!=(Complex &c)
{
	if(this->m_a!=c.m_a || this->m_b!=c.m_b)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main()
{
	Complex c1(1,2);
	Complex c2(2,3);
	if(c1==c2)
	{
		cout<<"相等"<<endl;
	}
	else
	{
		cout<<"不相等"<<endl;
	}
	if(c1 != c2)
	{
		cout<<"不相等"<<endl;
	}
	else
	{
		cout<<"相等"<<endl;
	}
	
	return 0;
}

当无法修改做操作数的类时使用全局变量进行重载,只能通过成员函数进行重载:

  1. =  
  2. []
  3. ()
  4. ->

只能通过全局函数进行重载 <<,

<<支持链式编程  cout<<c3<<endl;

类成员函数无法实现<<操作符重载,因为拿不到cout这个类的源码;

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值