运算符重载用来适应不同的数据类型
仅仅是语法的方便,实则是函数
如果左边不是自定义对象,只能用全局函数完成运算符重载
举例:
main.cpp
#include <iostream>
#include"person.h"
using namespace std;
int main()
{
Person ob1("lucy",100,40);
Person ob2("dd",23,55);
cout<<ob1<<ob2;
cout << "Hello World!" << endl;
return 0;
}
#include "person.h"
#include<string.h>
Person::Person()
{
}
Person::Person(string name, int num, float score)
{
this->name = name;
this->num = num;
this->score = score;
}
ostream& operator<<(ostream &out, Person &ob)
{
out<<ob.name<<","<<ob.num<<","<<ob.score<<endl;
return out;
}
#ifndef PERSON_H
#define PERSON_H
#include<string>
#include<iostream>
using namespace std;
class Person
{
friend ostream& operator<<(ostream& out,Person& ob);
public:
Person();
Person(string name,int num,float score);
private:
string name;
int num;
float score;
};
ostream& operator<<(ostream& out,Person& ob);
#endif // PERSON_H