C++运算符重载3

重载输入输出流运算符


代码

#include <iostream>
#include <cstdlib>
#include <limits>
using namespace std;
class MyComplex {
public:
    double a, b;
    MyComplex() {};
    MyComplex(double A, double B) {
        a = A;
        b = B;
    }
    MyComplex operator+(const MyComplex& c);
    MyComplex operator-(const MyComplex& c);
    MyComplex operator*(const MyComplex& c);
    MyComplex operator/(const MyComplex& c);
    friend ostream& operator <<(ostream& os, const MyComplex& z);
    friend istream& operator >>(istream& is, MyComplex& z);
};
ostream& operator <<(ostream& os, const MyComplex& z) { 
    os << "(";
    os.unsetf(std::ios::showpos);
    os << z.a;
    os.setf(std::ios::showpos);
    os << z.b << "i)";
    return os;
}
istream& operator >>(istream& is,  MyComplex& z) {
    is >> z.a >> z.b;
    return is;
}
MyComplex MyComplex::operator+(const MyComplex& c) {
    return MyComplex(a + c.a, b + c.b);
}
MyComplex MyComplex::operator-(const MyComplex& c) {
    return MyComplex(a - c.a, b - c.b);
}
MyComplex MyComplex::operator*(const MyComplex& c) {
    return MyComplex(a * c.a, b * c.b);
}
MyComplex MyComplex::operator/(const MyComplex& c) {
    return MyComplex(a / c.a, b / c.b);
}
int main() {
    MyComplex z1, z2;
    cin >> z1;
    cin >> z2;
    cout << z1 <<" "<< z2 << endl;  //z1和z2之间间隔1个空格
                                      // GCC及VC编译器在调试模式下会暂停,便于查看运行结果
#if ( defined(__DEBUG__) || defined(_DEBUG) )
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin.get();
#endif
    return 0;
}

相关说明

ostream这个类提供了setf()函数,可以设置数值输出时是否要带标志位。【具体可以查阅 setf 函数

ostream os;
os.setf(std::ios::showpos);
os << 12;  //输出 +12

ostream这个类还提供了unsetf()函数,可以将某个标志位取消。

当你使用了setf,输出复数 1+2i 时

os.setf(std::ios::showpos);
os << real << image << "i";

就会显示“+1+2i”。怎样把实部前面的那个正号去掉呢?
此时,你需要用两条语句,分别输出复数的实部和虚部。输出实部前,使用
os.unsetf(std::ios::showpos);
输出虚部前,使用
os.setf(std::ios::showpos);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容