- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
[理学]4_运算符重载
假定下面程序输出为 5hello, 请问该补写些什么? #include iostream using namespace std; class CStudent{ public: int nAge; }; int main(){ CStudent s ; s.nAge = 5; cout s hello; return 0; } * 写法1: ostream operator (ostream o, const CStudent s){ o s.nAge; return o; } 写法2: ostream operator (ostream o, const CStudent s){ o s.nAge; return o; } 写法3: ostream operator( ostream o,const CStudent s){ o s.nAge ; return o; } 可以,但是效率比较低 不行,有可能 runtime error,因为返回值引用的对象已经不存在了 可以,而且效率较高 * 事实上在 iostream里是将 << 重载成成员函数 class ostream { ostream operator(int n) { Output(n); return * this; } }; 那么 cout n ++ n; 的函数调用形式是什么呢? * 是: (cout.operator(n++)).operator(n); 实际上,这条语句可以直接写在程序里,其效果和 cout n++ n; 完全一样 * 运算符重载示例1 一个 PhoneNumber 类的对象能够通过cin, cout 输入输出的例子 int main(){ PhoneNumber phone; // create object phone cin phone; cout phone endl; return 0; } 输入: (123) 456-7890 输出: (123) 456-7890 * #include iostream #include iomanip //这个是为了后文的 setw using namespace std; * class PhoneNumber { private: char areaCode[ 4 ]; // 3-digit area code char exchange[ 4 ]; // 3-digit exchange char line[ 5 ]; // 4-digit line friend ostream operator( ostream output, const PhoneNumber num ); friend istream operator( istream, PhoneNumber ); // cin是istream类的 }; ostream operator(ostream output, const PhoneNumber num ){ output ( num.areaCode ) num.exchange - num.line; return output; // enables cout a b c; } * istream operator( istream input, PhoneNumber num ) { input.ignore(); // skip “(” input setw( 4 ) num.areaCode; // input area code input.ignore( 2 ); // skip “)” and space input setw( 4 ) num.exchange; // input exchange input.ignore(); // skip dash “-” input setw( 5 ) num.line; // input line return input; // enables cin a b c; } // setw(n) 指定下一次只读取 n-1个字符 int main(){ PhoneNumber phone; // crea
文档评论(0)