欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > c/c++ >内容正文

c/c++

C++重载>>和<<输入和输出运算符)

发布时间:2025/4/5 c/c++ 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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++重载>>和<<输入和输出运算符)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。