美文网首页
C++ - 流插入运算符重载

C++ - 流插入运算符重载

作者: Mitchell | 来源:发表于2016-01-20 15:42 被阅读90次
    • 假设输出为 5Hello,该补写什么
    using namespace std;
    class CStudent {
    public:
        int nAge;
    };
    //插入运算符的重载
    ostream& operator<<(ostream& o,const CStudent& s){
        o<<s.nAge;
        return o;
    }
    int main(int argc, const char * argv[]) {
        CStudent s;
        s.nAge = 5;
        cout<<s<<"hello";
        return 0;
    }
    
    • 需求,有实部虚部的 Complex 类输入 a+bi,将 a 给实部,b 给虚部,输出 Complex 以 a+bi 的形式输出:
    #include <iostream>
    #include <string>
    #include <cstdlib>
    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& os, Complex& c);
    };
    ostream& operator <<(ostream& os, const Complex& c){
        os<<c.real<<"+"<<c.imag<<"i";
        return os;
    }
    istream& operator >>(istream& is, Complex& c){
        //1.先将 a+bi 作为字符串读入
        string s;
        is>>s;
        //2.处理 a+bi 字符串
        int pos = s.find("+",0);
        string sTmp = s.substr(0,pos);
        //atof 库函数能将 const char* 指针指向的内容转换成 float
        c.real = atof(sTmp.c_str());
        sTmp = s.substr(pos+1,s.length()-pos-2);
        c.imag = atof(sTmp.c_str());
        return is;
    }
    int main(int argc, const char * argv[]) {
        Complex c;
        cin>>c;
        cout<<c;    
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:C++ - 流插入运算符重载

          本文链接:https://www.haomeiwen.com/subject/wmllkttx.html