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++重载<<>>的主要内容,如果未能解决你的问题,请参考以下文章