2015-第6周项目6-复制模板类(3)

(3)友元函数提供了一种非成员函数访问私有数据成员的途径,模板类使类中的数据成员的类型变得灵活,这两种技术可以结合起来用。要求在前面方案的基础上支持用友员函数实现的加法。





代码:

#include <iostream>
#include <cstring>

using namespace std;
template<class T>
class Complex
{
public:
    Complex()
    {
        real=0;
        imag=0;
    }
    Complex(T r,T i)
    {
        real=r;
        imag=i;
    }
    Complex complex_add(const Complex &c2);
    Complex complex_minus(const Complex &c2);
    Complex complex_multiply(const Complex &c2);
    Complex complex_divide(const Complex &c2);
    template<class T2>
    friend Complex<T2> add_complex(const Complex<T2> &c1,const Complex<T2> &c2);

    void display();
private:
    T real;
    T imag;
};
template<class T>
Complex<T> add_complex(const Complex<T> &c1, const Complex<T> &c2)
{
    Complex<T> c;
    c.real=c1.real+c2.real;
    c.imag=c1.imag+c2.imag;
    return c;
}
template<class T>
Complex<T> Complex<T>::complex_add(const Complex<T> &c2)
{
    Complex<T> c;
    c.real=real+c2.real;
    c.imag=imag+c2.imag;
    return c;
}
template<class T>
Complex<T> Complex<T>::complex_minus(const Complex<T> &c2)
{
    Complex<T> c;
    c.real=real-c2.real;
    c.imag=imag-c2.imag;
    return c;
}
template<class T>
Complex<T> Complex<T>::complex_multiply(const Complex<T> &c2)
{
    Complex <T> c;
    c.real=real*c2.real-imag*c2.imag;
    c.imag=imag*c2.real+real*c2.imag;
    return c;

}
template<class T>
Complex<T> Complex<T>::complex_divide(const Complex<T> &c2)
{
    Complex <T> c;
    T d=c2.real*c2.real+c2.imag*c2.imag;
    c.real=(real*c2.real+imag*c2.imag)/d;
    c.imag=(imag*c2.real-real*c2.imag)/d;
    return c;
}
template<class T>
void Complex<T>::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( );
    Complex<double> c8;
    c8=add_complex(c4,c5);  //调用友员函数支持加法运算,有两个形参
    cout<<"c4+c5=";
    c8.display( );
    return 0;
}






你可能感兴趣的:(C++,类)