C++重载<<>>

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++重载<<>>相关的知识,希望对你有一定的参考价值。

#include<iostream>
using namespace std;
class Complex{
    public:
        Complex(double r=0,double i=0){real=r;imaginary=i;}
        
        const Complex operator+(const Complex& right)const{
            return Complex(real+right.real,imaginary+right.imaginary);
        }
    friend    ostream& operator<<(ostream& os,const Complex& c);
    friend    istream& operator>>(istream& os,Complex& c);
    private:
        double real,imaginary;
};
ostream& operator<<(ostream& os,const Complex& c){
    if(c.real==0&&c.imaginary==0)os<<"0";
    if(c.real!=0) os<<c.real;
    if(c.imaginary!=0){
        if(c.imaginary!=0){
            if(c.imaginary>0&&c.real!=0)
                os<<"+";
            os<<c.imaginary<<"i";
        }
    }
    return os;
}
istream& operator>>(istream& is,Complex& c){
    cout<<"Please input a Complex:"<<endl;
    return is>>c.real>>c.imaginary;
}
int main()
{
    Complex c1,c2;
    cin>>c1;
    cin>>c2;
    cout<<c1+c2<<endl;
    return 0;
}

 

以上是关于C++重载<<>>的主要内容,如果未能解决你的问题,请参考以下文章

C++重载<<>>

C++ 输入/输出运算符重载

运算符 + 重载 C++

模板化一个类,然后重载运算符 (C++)

C++ 运算符重载和继承

c++重载运算符两种形式的选择