“c++“中的重载

重载注意点

一个运算符在同一个类型只能被重载一次

重载的函数名为operator和一个重载运算符

(如重载加号就operator+)表示重载加号

二种重载方式

一个是在类中重载(常用于单目运算符)

class Data
{
public:
	
	Data(int year, int month) :year(year), month(month) { };
	Data operator+(Data& object)
	{
		return Data(object.month + this->month, object.year + this->year);
	}
	//在类中重载一个加号
protected:
	int year;
	int month;
};
int main()
{

   Data d1(15, 20);
	Data d2(20, 30);
	//通过重载类中运算符
	Data d3 = d1.operator+(d2);
	Data d4 = d1 + d2;
	//这二者都是一样的一个是显示调用一个是隐式调用
}

一个是以友元的方式重载(常用于双目运算符)

class people
{
public:
	people(int num, int c) :num(num), c(c) {};
	friend people operator+(people& object, people& object1);
protected:
	int num;
	int c;
};
people operator+(people& object, people& object1)
{
	return people(object.num + object1.num, object.c + object1.c);
}
int main()
{
    people p1(15, 20);
	people p2(20, 15);
	people p3 = p1 + p2;
	people p4 = operator+(p1, p2);
	//同 一个是显示调用一个是隐式调用
	//隐式调用就是编译器把+自动转化为函数去使用了
    return 0;
	
}

流重载

 输入流重载

 输出流重载

//使用就是通过一个运算符输入或者输出整个对象里面的数据

流重载只能以友元的方式去重载

class Data
{
public:
	
	Data(int month, int year) :year(year), month(month) { };
	Data operator+(Data& object)
	{
		return Data(object.month + this->month, object.year + this->year);
	}
	//流重载只能以友元的方式重载
	friend ostream& operator<<(ostream& out, Data& object)
	{
		out << object.month << "  " << object.year << endl;
		return out;
	}
	friend istream& operator>>(istream& in, Data& object)
	{
		in >> object.month >> object.year;
		return in;
	}
	void printfdata()
	{
		cout << this->month << "  " << this->year << endl;
	}
protected:
	int year;
	int month;
};

 操作演示

int main()
{
	Data d1(15, 20);
	Data d2(20, 30);
	Data d3 = d1.operator+(d2);
	Data d4 = d1 + d2;
	cout << "流重载输出 ";
	cout << d3;
	cout << "调用函数输出 ";
	d3.printfdata();
	cout << "流重载输入 ";
	cin >> d1;
	cout << "流重载输出 ";
	cout << d1 << endl;
	return 0;
}

 重载各种运算符操作

 前置++

 后置++ 

	Data operator++()//函数内我标记表示前置++
	{
		return Data(++this->month, ++this->year);//
	}
	Data operator++(int)//i给个int告诉编译器这个是后置++
	{
		return Data(this->month++, this->year++);
	}

理解重载本质:

就是如果重载了运算符后你在运用这个运算符的时候你就是调用这个函数

然后进行函数相应的操作。

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gfxr1212

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值