重载输入输出流:Overload Ostream And Istream

本文介绍了一个使用C++模板类实现的复数类,该类支持基本的复数运算如加法,并提供了输入输出操作符以方便显示复数。通过实例演示了如何创建和操作复数对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include<iostream>
using namespace std;

template<class T>
class complex
{
 template<class T>
 friend ostream& operator<<(ostream& os,complex<T>& z);
 template<class T>
 friend istream& operator>>(istream& ist,complex<T>& z);
private:
 T img;
 T real;
public:
 complex(T r,T i):real(r),img(i)
 {}
 complex():img(0),real(0)
 {}
 ~complex(void)
 {}
 complex operator+(const complex& z)
 {
  return complex(real+z.real,img+z.img);
 }
 void operator=(const complex& z)
 {
  real=z.real;
  img=z.img;
 }
};

 

template <class T>
ostream& operator<<(ostream& os,complex<T>& z)
{
 os<<"("<<z.real<<","<<z.img<<")"<<endl;
 return os;
}

template <class T>
istream& operator>>(istream& ist,complex<T>& z)
{
 cout<<"the real is ";
 ist>>z.real;
 cout<<" the img is ";
 ist>>z.img;
 return ist;
}
int _tmain(int argc, _TCHAR* argv[])
{
 complex<int> z1(1,2),z2(3,4),z3;
 z3=z1+z2;
 cout<<"z3 is "<<z3<<endl;
 cin>>z3;
 cout<<"z3 is "<<z3<<endl;
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值