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

  • 假设输出为 5Hello,该补写什么
using namespace std;
class CStudent {
public:
    int nAge;
};
//插入运算符的重载
ostream& operator<<(ostream& o,const CStudent& s){
    o<
  • 需求,有实部虚部的 Complex 类输入 a+bi,将 a 给实部,b 给虚部,输出 Complex 以 a+bi 的形式输出:
#include 
#include 
#include 
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<>(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++ - 流插入运算符重载)