运算符重载基本概念
运算符重载(operator overloading)只是一种”语法上的方便”,也就是它只是另一种函数调用的方式。
运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
案例: 重载左移操作符(<<),使得 cout 可以输出对象。
#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; //重新实现 输出格式
return out; //每次执行为 返回值得到cout
}
int main(int argc, char *argv[])
{
Person ob1("lucy",18);
operator<<(cout, ob1)<<endl;
// 进行优化 去掉operator,第一个参数 放在运算符<<的左边 第二个参数 放在运算符<<的右边
cout<<ob1<<endl;//等价operator<<(cout, ob1);
Person ob2("bob",19);
cout<<ob1<<" "<<ob2<<endl;
return 0;
}