C++重载>>和<<输入和输出运算符)
生活随笔
收集整理的这篇文章主要介绍了
C++重载>>和<<输入和输出运算符)
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
在C++中,标准库本身已经对左移运算符<<和右移运算符>>分别进行了重载,使其能够用于不同数据的输入输出,但是输入输出的对象只能是 C++ 内置的数据类型(例如 bool、int、double 等)和标准库所包含的类类型(例如 string、complex、ofstream、ifstream 等)。
如果我们自己定义了一种新的数据类型,需要用输入输出运算符去处理,那么就必须对它们进行重载。本节以前面的 complex 类为例来演示输入输出运算符的重载。
其实 C++ 标准库已经提供了 complex 类,能够很好地支持复数运算,但是这里我们又自己定义了一个 complex 类,这样做仅仅是为了教学演示。
本节要达到的目标是让复数的输入输出和 int、float 等基本类型一样简单。假设 num1、num2 是复数,那么输出形式就是:
#include <iostream> using namespace std; class complex { public:complex();complex(double a);complex(double a, double b);friend complex operator+(const complex & A, const complex & B);friend complex operator-(const complex & A, const complex & B);friend complex operator*(const complex & A, const complex & B);friend complex operator/(const complex & A, const complex & B);friend istream &operator>>(istream & in ,complex & A);friend ostream &operator<<(ostream & out ,complex & A);void display()const; private:double real; //复数的实部double imag; //复数的虚部 }; complex::complex() {real = 0.0;imag = 0.0; } complex::complex(double a) {real = a;imag = 0.0; } complex::complex(double a, double b) {real = a;imag = b; } //打印复数 void complex::display()const {cout<<real<<" + "<<imag<<" i "; } //重载加法操作符 complex operator+(const complex & A, const complex &B) {complex C;C.real = A.real + B.real;C.imag = A.imag + B.imag;return C; } //重载减法操作符 complex operator-(const complex & A, const complex &B) {complex C;C.real = A.real - B.real;C.imag = A.imag - B.imag;return C; } //重载乘法操作符 complex operator*(const complex & A, const complex &B) {complex C;C.real = A.real * B.real - A.imag * B.imag;C.imag = A.imag * B.real + A.real * B.imag;return C; } //重载除法操作符 complex operator/(const complex & A, const complex & B) {complex C;double square = B.real * B.real + B.imag * B.imag;C.real = (A.real * B.real + A.imag * B.imag)/square;C.imag = (A.imag * B.real - A.real * B.imag)/square;return C; }//重载输入操作符 istream & operator>>(istream & in ,complex & A) {in >>A.real>>A.imag;return in ; }//重载输出操作符 ostream & operator<<(ostream &out ,complex &A) {out <<A.real<<"+"<<A.imag<<" i ";return out ; }int main() {complex c1(3, 4);complex c2(1, 2);complex c3;c3 = c1 + c2;cout<<"c1 + c2 = "<<c3<<endl;//c3.display();//cout<<endl;c3 = c1 - c2;cout<<"c1 - c2 = "<<c3<<endl;//c3.display();//cout<<endl;c3 = c1 * c2;cout<<"c1 * c2 = "<<c3<<endl;//c3.display();//cout<<endl;c3 = c1 / c2;cout<<"c1 / c2 = "<<c3<<endl;//c3.display();//cout<<endl;return 0; } c1 + c2 = 4+6 i c1 - c2 = 2+2 i c1 * c2 = -5+10 i c1 / c2 = 2.2+-0.4 i总结
以上是生活随笔为你收集整理的C++重载>>和<<输入和输出运算符)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: C++用顶层函数重载操作符(三)用友元优
- 下一篇: C++函数模板(一)