??????????????????????创做不易,麻烦点个关注????????????????????????
??????????????????文末有惊喜!献舞一支!????????????????????
上节实现了<<、>>输入输出运算符重载,那么我们怎么实现下面这样的情况呢?
?
这里就是上一节我们输出的时候,第二参数传的是引用类型。
结果:
代码:
#include <iostream>
#include <string>
#include "array.h"
using namespace std;
class Person
{
friend ostream& operator<<(ostream &out,Person ob);
friend istream& operator>>(istream &in,Person &ob);
friend Person operator+(Person &ob1,Person &ob2);
private:
int num;
string name;
float score;
public:
Person(){}
Person(int num,string name,float score):num(num),name(name),score(score){}
};
//全局函数重载operator<< 输出运算符
ostream& operator<<(ostream &out,Person ob){
out<<ob.num<<" "<<ob.name<<" "<<ob.score<<endl;
return out;
}
//全局函数重载operator>> 输入运算符
istream& operator>>(istream &in,Person &ob){
in>>ob.num>>ob.name>>ob.score;
return in;
}
//全局函数重载+运算符
Person operator+(Person &ob1,Person &ob2){
Person tmp;
tmp.num = ob1.num+ob2.num;
tmp.name = ob1.name+ob2.name;
tmp.score = ob1.score+ob2.score;
return tmp;
}
int main()
{
Person Jery{101,"Jery",99.9f};
Person Tom{102,"Tom",98.9f};
cout<<Jery+Tom<<endl;
return 0;
}
代码:
#include <iostream>
#include <string>
#include "array.h"
using namespace std;
class Person
{
friend ostream& operator<<(ostream &out,Person ob);
friend istream& operator>>(istream &in,Person &ob);
//friend Person operator+(Person &ob1,Person &ob2);
private:
int num;
string name;
float score;
public:
Person(){}
Person(int num,string name,float score):num(num),name(name),score(score){}
//成员函数实现重载加法运算符
Person operator+(Person &ob)
{
Person tmp;
tmp.num = num + ob.num;
tmp.name = name + ob.name;
tmp.score = score + ob.score;
return tmp;
}
};
//全局函数重载operator<< 输出运算符
ostream& operator<<(ostream &out,Person ob){
out<<ob.num<<" "<<ob.name<<" "<<ob.score<<endl;
return out;
}
//全局函数重载operator>> 输入运算符
istream& operator>>(istream &in,Person &ob){
in>>ob.num>>ob.name>>ob.score;
return in;
}
int main()
{
Person Jery{101,"Jery",99.9f};
Person Tom{102,"Tom",98.9f};
//Jery + Tom ==> Jery.operator+(Tom)
//cout<<Jery+Tom<<endl;
cout << Jery.operator+(Tom) <<endl;
return 0;
}
??您的支持??是我最大的动力??相互学习??共同进步??一起搞钱??动动发财的小手??
? ????????????????????十星好评,Erike的专用模板?????????????????????
什 ?么 ?您 ?要 ?打 ?赏 ?谢 ? ?谢 ? ?老 ? 板!老 ? ?板 ? ?大 ? ?气!?
?