运算符重载
人在世上练,刀在石上磨
1、重载运算符的概述
运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
运算符重载的目的:简化操作 让已有的运算符 适应适应不同的数据类型。
语法:函数的名字由关键字operator及其紧跟的运算符组成
比如:重载+运算符 == > operator+ 重载=号运算 ==>operator=
注意:重载运算符 不要更改 运算符的本质操作(+是数据的相加 不要重载成相减)
2、运算符<<的重载
#include <iostream>
#include<string.h>
using namespace std;
class Person
{
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;
}
};
int main(int argc, char *argv[])
{
Person ob1("lucy",18);
//普通的成员函数 遍历信息
//ob1.printPerson();
//cout默认输出方式 无法识别 自定义对象 输出格式
//cout<<ob1<<endl;//err
return 0;
}
截图:
解决上述问题 需要重载<<
解决办法:将operator<<设置成友元:
完整代码:
#include <iostream>
#include<string.h>
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=cout, ob =ob1
{
//重新实现 输出格式
out<<ob.name<<", "<<ob.num;
//每次执行为 返回值得到cout
return out;
}
int main(int argc, char *argv[])
{
Person ob1("lucy",18);
//普通的成员函数 遍历信息
//ob1.printPerson();
//cout默认输出方式 无法识别 自定义对象 输出格式
//cout<<ob1<<endl;//err
//运算符重载的调用方式1:
operator<<(cout, ob1)<<endl;
//运算符重载的调用方式2:
//对方法1 进行优化 去掉operator,第一个参数 放在运算符<<的左边 第二个参数 放在运算符<<的右边
cout<<ob1<<endl;//等价operator<<(cout, ob1);
Person ob2("bob",19);
cout<<ob1<<" "<<ob2<<endl;
return 0;
}
运行结果: