/*
* 程序的版权和版本声明部分
* Copyright (c)2012, 烟台大学计算机学院学生
* All rightsreserved.
* 文件名称: object.cpp
* 作者: 董万鹏
* 完成日期: 2013年 4 月 15 日
* 版本号: v1.0
* 输入描述:无
* 问题描述:无
* 程序输出:无
*/
#include <iostream>
using namespace std;
template<class Type>
class Complex
{
public:
Complex( ){real=0;imag=0;}
Complex(Type r,Type i){real=r;imag=i;}
Complex complex_add(Complex &c2);
friend Complex<Type> add_complex(Complex<Type> &c1, Complex<Type> &c2);
void display( );
private:
Type real;
Type imag;
};
template<class Type>
Complex<Type> Complex<Type>::complex_add(Complex<Type> &c2)
{
Complex<Type> c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
//利用了模板的友元函数的定义
template<class Type>
Complex<Type> add_complex(Complex<Type> &c1, Complex<Type> &c2)
{
Complex<Type> c;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
return c;
}
template<class Type>
void Complex<Type>::display( )
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int main( )
{
Complex<int> c1(3,4),c2(5,-10),c3;
c3=c1.complex_add(c2);
cout<<"c1+c2=";
c3.display( );
Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6;
c6=c4.complex_add(c5);
cout<<"c4+c5=";
c6.display( );
Complex<int> c7;
c7=add_complex(c1,c2);
cout<<"c1+c2=";
c7.display( );
return 0;
}
任务55555、、、
最新推荐文章于 2024-11-20 20:37:59 发布