【C++运算符重载】运算符重载(二)
        【摘要】 @TOC 前言本节课是对上节的示例,我给大家把一些运算符都写一下,方便大家使用不同的运算符 重载例子class Student{public:	int age;	Student()	{		age = 10;	}	int operator -()//一元运算符	{		return -age;	}	//<<	ostream& operator <<(ostream o)	{		o << this...
    
    
    
    @TOC
前言
本节课是对上节的示例,我给大家把一些运算符都写一下,方便大家使用不同的运算符
重载例子
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、避免过度使用
什么时候用?
            【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
                cloudbbs@huaweicloud.com
                
            
        
        
        
        
        
        
        - 点赞
- 收藏
- 关注作者
 
             
           
评论(0)