【运算符重载】
一、
重载运算符就是对已有的运算符进行重新定义,赋予其另一种功能,以适应不同的数据类型。
目的:简化操作,适应不同的数据类型。
语法:operator 紧跟着 需要重载的运算符。
比如 重载+号:operator +
只能使用成员函数重载的运算符有:=、()、[]、->
只能使用成员函数重载是为了防止出现: 1 = x, 1[x], 1->x, 1(x)这样的合法语句
二、运算符<<的重载
一般用于输出自定义类型
class Person{
friend ostream & operator<<(ostream &out, Person &ob);
private:
string name;
int age;
public:
Person(void)
{
this->name="";
this->age=0;
}
Person(string name,int age)
{
this->name = name;
this->age = age;
}
};
ostream & operator<<(ostream &out, Person &ob)
{
cout<<"姓名:"<<ob.name<<",年龄是:"<<ob.age; //当name和age是private和protected时候将此函数成为类的友元
return out;
}
void test08()
{
//定义并初始化一个Person对象
Person ob("bob",19);
cout<<ob;
}
运行结果:
注:为了迭代使用<<,所以我们要返回out
+的重载
在自定义类型的时候,系统并不知道这个类型相加所得结果是如何计算的。所以需要我们重载+号运算符。
比如,我们创建一个Person类,里面有姓名和年龄,所以此时我们想个Person对象相加,需要我们重载+号运算符,根据需求来编写代码。
案例:实现Person类(string name,int age)的相加
可以使用成员函数和非成员函数,使用成员函数可以减少一个参数的传递
1、使用成员函数
Person & operator +(Person &ob)
{
static Person tmp;
tmp.name = this->name +ob.name;
tmp.age = this->age+ob.age;
return tmp;
}
void test08()
{
//定义并初始化一个Person对象
Person ob("bob",19);
Person ob1("lucy",20);
cout<<ob+ob1;
}
运行结果:
2、使用非成员函数
Person & operator +(Person &ob1,Person &ob2)
{
static Person ob;
ob.name = ob1.name+ob2.name;
ob.age =ob1.age + ob2.age;
return ob;
}
void test08()
{
//定义并初始化一个Person对象
Person ob("bob",19);
Person ob1("lucy",20);
cout<<ob+ob1;
}
运行结果:
总结:如果需要使用Person数据并且权限不够的话,而且重载函数是非成员函数,就需要作为类的友元函数
重载++(包括前置++和后置++)
1、前置++,即先加加,后使用 operarot ++()
案例:有一个Person类,使用++的时候,让name增加一个ing,age加1
//成员函数
Person& operator ++()//先加加,再使用
{
this->name=this->name.append("ing");
this->age++;
return *this;
}
void test08()
{
//定义并初始化一个Person对象
Person ob("bob",19);
ob++;
cout<<ob;
}
运行结果:
2、后置++ operator++(int) 需要占位符
Person & operator ++(int)
{
static Person old; //保存旧的
old = *this;
this->name = this->name.append("ing");
this->age++;
return old; //返回旧的
}
运行结果:
总结:成员函数时可以少传一个参数,非成员函数的话就需要多串一个参数,并且作为类的友元。
--运算符重载
和++同理
仿函数:()的重载
class Fun{
public: int my_add(int x,int y)
{
return x+y;
}
int operator()(int x,int y)
{
return x+y;
}
};
void test08()
{
Fun fun;
cout<<fun(10,20)<<endl;
cout<<fun.my_add(10,20)<<endl;
}
运行结果: