【C++运算符重载】运算符重载(二)

前言

本节课是对上节的示例,我给大家把一些运算符都写一下,方便大家使用不同的运算符


重载例子

class Student
{
public:
	int age;
	Student()
	{
		age = 10;
	}

	int operator -()//一元运算符
	{
		return -age;
	}

	//<<
	ostream& operator <<(ostream o)
	{
		o << this->age;
		return o;
	}

	istream& operator >>(istream o)
	{
		o >> this->age;
		if (o.fail())
		{
			cout << "o>> fail" << endl;
		}
		return o;
	}

	int operator =(int a)
	{
		age = a;
		return age;
	}

	int operator [](int a)
	{
		switch (a)
		{
		case 1:
			return age;
			break;
		}
	}

	//左++   类内无参数
	int operator ++()
	{
		return ++age;
	}

	//右++   参数n代表右++
	int operator ++(int n)
	{
		return age++;
	}
};

一元运算符重载:类外一个参数,类内无参数

+,-,&,*, 
	正,负,取地址,内存操作符
~, !

输入<< 输入>>
">>"ostream "<<"istream两个类
输入

ostream& operator <<(ostream o)
{
	o << this->age;
	return o;
}

返回值为osteam&方便连续输出
参数为ostream
在类外需要写两个参数

	istream& operator >>(istream o)
	{
		o >> this->age;
		if (o.fail())
		{
			cout << "o>> fail" << endl;
		}
		return o;
	}

返回值为isteam&方便连续输入
参数为istream
在类外需要写两个参数
istream::fail()函数判断输入是否出错

赋值 “=”
他只能类内

	int operator =(int a)
	{
		age = a;
		return age;
	}
符合赋值运算符
	+=, -+, *=, /=,%=, <<=, >>= , ^=,&=, |=
		建议类内,类外也行

下标运算符:只能类内

	int operator [](int a)
	{
		switch (a)
		{
		case 1:
			return age;
			break;
		}
	}

内部实现:可以通过switch判断要返回的变量

左++/左–

	int operator ++()
	{
		return ++age;
	}

类内无参数

右++/左–

	int operator ++(int n)
	{
		return age++;
	}

右++:需要参数n,如果没有,则为左++


左–/右–和上相同

重载类型转换

特点
	1、没有显式返回类型
		但是要写返回值
	2、没有参数
	3、必须定义成类的成员函数
	4、不应该改变对象的内容,所以是const函数
	5、避免过度使用
什么时候用?
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

人才程序员

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

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

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

打赏作者

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

抵扣说明:

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

余额充值