流插入和流提取运算符的重载
cout是在iostream中定义的,是ostream类的对象。cin是istream类的对象。测试代码如下:
#include <iostream> #include <string> #include <cstdlib> using namespace std; class Complex { private : int real, img; public: friend ostream & operator <<(ostream & o, const Complex &c); friend istream & operator >> (istream & is,Complex &c); }; ostream &operator <<(ostream &o, const Complex &c) { o << c.real << '+' << c.img << 'i'; return (o); } istream &operator >> (istream & is, Complex &c) { string s; is >> s; int p = s.find('+', 0); string sTmp = s.substr(0, p); c.real = atof(sTmp.c_str()); sTmp = s.substr(p + 1, s.length() - p - 2); c.img = atof(sTmp.c_str()); return is; } int main() { Complex c; int n = 0; cin >> c >> n; cout << c <<","<< n; return 0; }
参考链接:
https://www.coursera.org/learn/cpp-chengxu-sheji
本人博客已迁往 https://chenlongxiabc.github.io 欢迎访问。
博客内容均为自己编写,其中参考了相关内容。若有侵权他人请联系我,并对此表示歉意。若要转载或是其他用途,请联系我。我的邮箱diegefulan@hotmail.com