知识点5 运算符重载
1、运算符重载的概述
运算符重载,就是对已有的运算符进行重新定义,赋予其另外一种功能,以适应不同数据类型,从而达到简化操作的目的。
语法:使用operator然后紧跟重载的运算符构成。
2、运算符<<的重载
#include <iostream>
#include <cstring>
using namespace std;
class Person
{
//设置成友元在函数内访问person类中的所有数据
friend ostream& operator<<(ostream &out, Person &ob);
private:
char* name;
int num;
public:
Person(char* name, int num)
{
this->name = new char[strlen(name)+1];
strcpy(this->name,name);
this->num = num;
cout << "有参构造" << endl;
}
void printPerson(void)
{
cout << "name = " << name << ", num = " << num << endl;
}
~Person()
{
if(this->name != NULL)
{
delete [] this->name;
this->name = NULL;
}
cout << "析构函数" << endl;
}
};
ostream& operator<<(ostream &out, Person &ob)
{
//重新实现输出搁置
out << ob.name << ", " << ob.num;
//每次执行返回值得到cout
return out;
}
int main()
{
Person ob1("Momoka",19);
Person ob2("Monika",18);
//运算符重载的调用方法1
operator<< (cout, ob1) << endl;
//调用方法2
cout << ob1 << endl;
cout << ob1 << " " << ob2 << endl;
}
运算符+的重载 全局函数作为友元完成运算符+的重载
Person operator+(Person &ob1, Person &ob2)
{
//字符串相加
char *tmp_name = new char[strlen(ob1.name)+strlen(ob2.name)+1];
strcpy(tmp_name,ob1.name);
strcat(tmp_name,ob2.name);
//num相加
int tmp_num = ob1.num + ob2.num;
Person tmp(tmp_name, tmp_num);
//释放tmp的空间
if(tmp_name != NULL)
{
delete [] tmp_name;
tmp_name = NULL;
}
return tmp;
}
成员函数完成运算符+的重载
Person operator+(Person &ob)
{
//this-> &ob1
//字符串相加
char *tmp_name = new char[strlen(this->name)+strlen(ob.name)+1];
strcpy(tmp_name,this->name);
strcat(tmp_name,ob.name);
//num相加
int tmp_num = this->num + ob.num;
Person tmp(tmp_name, tmp_num);
//释放tmp的空间
if(tmp_name != NULL)
{
delete [] tmp_name;
tmp_name = NULL;
}
return tmp;
}