首页 > 代码库 > 操作符重载.xml

操作符重载.xml

<style type="text/css"> pre{ line-height:1; color:#1e1e1e; background-color:#d2d2d2; font-size:16px;}.sysFunc{color:#627cf6;font-style:italic;font-weight:bold;} .selfFuc{color:#800080;} .bool{color:#d2576f;} .condition{color:#000080;font-weight:bold;} .key{color:#000080;} .var{color:#800000;font-style:italic;} .Digit{color:#ff00ff;font-weight:bold;} .includePre{color:#1e1e1e;} .operator?{color:#008000;font-weight:bold;} </style>

操作符重载

?
#include?<iostream>
#include?<string>
using?namespace?std;
?
//定义水果类
?class?Fruit
{
??string?name;
??string?colour;
public:
?????????friend?istream&?operator>>(istream&,Fruit&);????????????????????//?输入流
?????????friend?ostream&?operator<<(ostream&?out,const?Fruit&?fruit);???????//?输出流
?????????void?print()
?????????{
???????????????????cout<<colour<<"?"<<name<<endl;
?????????}
?
?????????Fruit(const?string?nst="apple",const?string?cst="green"):name(nst),colour(cst)
?????????{
?????????}
?
?????????~Fruit()
?????????{
?????????}
};
?
?
//重载操作符
ostream&?operator<<(ostream&?out,?const?Fruit?&s)
{
?????????out<<s.colour<<"?"<<s.name<<endl;
?????????return?out;
?
}
?
istream&?operator>>(istream&?in,Fruit?&s)
{
?????????in>>s.colour>>s.name;
?????????if?(!in)
?????????{
???????????????????cerr<<"Wrong?input!"<<endl;
?????????}
?????????return?in;
}
?
?
?

主程序:

?????????Fruit?apple;
?????????cin>>apple;
?????????cout<<apple;
?

本文使用?书画小说软件?发布,内容与软件无关,书画小说软件?更惬意的读、更舒心的写、更轻松的发布。

操作符重载.xml