C++运算符重载(一)

1.加号运算符重载

C++内置的数据类型是可以直接相加的

但是用户定义类型呢

也是可以的,不够这要求我们自己重载运算符

在系统内置函数中operator  运算符  ()

#include <iostream>
using namespace std;

class Person
{
public:
	Person  operator+(Person& p)
	{
		Person temp;
		temp.age = this->age + p.age;
		return temp;
	}
public:
	int age;
};

Person operator+(Person &p1,Person &p2)
{
	Person temp;
	temp.age= p1.age + p2.age;
	return temp;
}
int main()
{
	Person p1, p2;
	p1.age = 10;
	p2.age = 20;
	Person  p3 = p1.operator+(p2);
	Person  p4 = operator+(p1, p2);
	cout << p3.age << endl;
	cout << p4.age << endl;
}

  p1.operator+(p2);   ---》p1+p2

operator+(p1, p2);     --》p1+p2

当然* / - %也能重载 

不能滥用,函数定义和函数实现意义要一致

2.左移运算符重载 

C++中,可以对内定基础类型输出,

int a;

cout<<a;

class Person

{

        private:

                int m_a;        

                int m_b;

cout<<p;  这个是不能的。

但是能通过重载左移运算符输出

 首先,成员函数不能重载左移运算符

因为成员函数的调用必须先是对象 而  cout<<p;

cout在运算符的左边,显然是不行的

可以通过全局函数重载

#include <iostream>
using namespace std;

class Person
{
public:
	Person  (int a,int b)
	{
		 m_age=a;
		 m_num=b;
	}
public:
	int m_age;
	int m_num;
};

ostream& operator<<(ostream & cout, Person& p)//引用传入,引用返回,因为链式调用,返回值要为cout对象本身
{
	cout << p.m_age << "  " << p.m_num << endl;
	return cout;
}
int main()
{
	Person p1(10, 20);//要输出10,20两个数据
	cout << p1 << endl;
}

同理,>>运算符也可以 

3.递增运算符重载

这个我有点懵,前置++和后置++方式不同

#include <iostream>
using namespace std;
//++运算符重载

class Myint
{
public:
	Myint()
	{
		num = 0;
	}
	Myint&  operator++()//前置运算符要返回引用,因为前置运算符满足链式
	{
		num++;
		return *this;
	}

	Myint operator++(int)  //后置返回的是自增前的值
	{
		Myint temp = *this;
		num++;
		return temp;  //返回值,不能返回局部变量的引用
	}
public:
	int num;
};

ostream& operator<<(ostream &cout,Myint &myint)
{
	cout << myint.num << endl;
	return cout;
}
int main()
{	
	Myint myint;
	cout <<++myint << endl;
}

后置++重载可能会报错 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值