#include <iostream>
template <class numtype>
class Complex
{public:
Complex(){real=0,imag=0;}
Complex(numtype r,numtype i){real=r;imag=i;}
Complex complex_add( Complex );
template <class numtype> friend Complex<numtype> add_complex(Complex<numtype> ,Complex<numtype> );//有元成员函数
void display();
private:
numtype real;
numtype imag;
};
template <class numtype>
Complex<numtype> Complex<numtype>::complex_add(Complex<numtype> a)
{
Complex<numtype> c;
c.real=real+a.real;
c.imag=imag+a.imag;
return c;
}
template <class numtype>
Complex<numtype> add_complex(Complex<numtype> a,Complex <numtype> b)
{
Complex<numtype> c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return c;
}
template <class numtype>
void Complex<numtype>::display()
{
cout<<real<<","<<imag<<"i"<<endl;
}
int main( )
{
Complex<int> c1(3,4),c2(5,-10),c3;
c3=c1.complex_add(c2); //需要在模板类中有一个成员函数支持加法运算,有一个形参
std::cout<<"c1+c2=";
c3.display( );
Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6;
c6=c4.complex_add(c5);
std::cout<<"c4+c5=";
c6.display( );
Complex<int> c7;
c7=add_complex(c1,c2); //需要在模板类中有一个友员函数支持加法运算,有两个形参
std::cout<<"c1+c2=";
c7.display( );
system("pause");
return 0;
}
7_6友元复数模板类
最新推荐文章于 2023-02-07 15:25:50 发布