四、流插入(右移)和流提取(左移)运算符重载

来源:互联网 发布:软件测试技术教程 编辑:程序博客网 时间:2024/06/15 08:48

流插入(右移)和流提取(左移)运算符重载

一、讨论

问题:
1. cout << 5 << “this”; 为什么能够成立?
2. cout是什么?“<<” 为什么能用在 cout上?

回答:
1. cout 是在 iostream 中定义的, ostream 类的对象。
2. “ <<” 能用在cout 上是因为,在iostream里对 “ <<” 进行了重载。

新的问题:
考虑,怎么重载才能使得 cout << 5; 和 cout << “this” 都能成立?

思考:
有可能按以下方式重载成 ostream类的成员函数:

void ostream::operator<<(int n){    …… //输出n的代码    return;}

这时候
cout << 5 ; 即 cout.operator<<(5);
cout << “this”; 即 cout.operator<<( “this” );

新的问题:
怎么重载才能使得 cout << 5 << “this” ; 成立?

思考:
可不可以把上面的 cout.operator<<(5)=void 变成 cout.operator<<(5)=cout.operator<<。
于是cout << 5 << “this”就可以变成 cout.operator<<(5).operator<<(“this”);

即:

ostream & ostream::operator<<(int n){    …… //输出n的代码    return * this;}ostream & ostream::operator<<( const char * s ){    …… //输出s的代码    return * this;}

二、例题

假定c是Complex复数类的对象,现在希望写“ cout << c;”,就能以“ a+bi”的形式输出c的值,写“ cin>>c;”,就能从键盘接受“ a+bi”形式的输入,并且使得c.real = a,c.imag = b。

程序:

class Complex {    double real,imag;    public:        Complex( double r=0, double i=0):real(r),imag(i){ };    friend ostream & operator<<( ostream & os, const Complex & c);    friend istream & operator>>( istream & is,Complex & c);};ostream & operator<<( ostream & os,const Complex & c){    os << c.real << "+" << c.imag << "i"; //以"a+bi"的形式输出    return os;}istream & operator>>( istream & is,Complex & c){    string s;    is >> s; //将"a+bi"作为字符串读入, “a+bi” 中间不能有空格    int pos = s.find("+",0);    string sTmp = s.substr(0,pos); //分离出代表实部的字符串    c.real = atof(sTmp.c_str());//atof库函数能将const char*指针指向的内容转换成float     sTmp = s.substr(pos+1, s.length()-pos-2); //分离出代表虚部的字符串    c.imag = atof(sTmp.c_str());    return is;}int main(){    Complex c;    int n;    cin >> c >> n;    cout << c << "," << n;    return 0;}

三、小结

流插入和流提取运算符重载的方法是:

istream & istream::operator>>(int n){    …… //读取n的代码    return * this;}ostream & ostream::operator<<( const char * s ){    …… //输出s的代码    return * this;}
0 0
原创粉丝点击