重载流插入 << 和流提取 >> 运算符,使其能够直接输出复数的类型的数据:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex()
{
real=0;
imag=0;
}
Complex(double r, double i)
{
real=r;
imag=i;
}
Complex operator +(Complex &c2);
friend ostream& operator << (ostream &, Complex &);
friend istream& operator >> (istream &, Complex &);
private:
double real;
double imag;
};
Complex Complex::operator +(Complex &c2)
{
return Complex(real+c2.real, imag+c2.imag);
}
ostream& operator << (ostream &output, Complex &c)
{
output << "(" << c.real << "+" << c.imag << "i)" << endl;
return output;
}
istream& operator >> (istream &input, Complex &c)
{
cout << "请分别输入复数的实部和虚部:" << endl;
input >> c.real >> c.imag;
return input;
}
int main()
{
cout << "--------------直接使用重载输出流--------------" << endl;
Complex c1(2, 4), c2(6, 10), c3;
c3= c1+c2;
cout << c3;
cout << "--------------直接使用重载输入流--------------" << endl;
Complex c4, c5;
cin >> c4 >> c5;
cout << "c1=" << c4 << endl;
cout << "c2=" << c5 << endl;
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)