复数模板类

/* 
* 程序的版权和版本声明部分 
* Copyright (c)2014, 烟台大学计算机学院学生 
* All rightsreserved. 
* 文件名称: fibnacci.cpp 
* 作    者:高古尊 
* 完成日期:2014年4月12日 
* 版本号: v1.0 
* 
* 输入描述: 
* 问题描述: 
* 程序输出: 
* 问题分析: 
*/  
#include <iostream>
using namespace std;
template<class T>
class Complex
{
public :
    Complex(T a,T b);
    Complex()
    {
        real=0,imag=0;
    }
    Complex complex_add(Complex &);
    Complex complex_jian(Complex &);
    Complex complex_cheng(Complex &);
    Complex complex_chu(Complex &);
    void display( );
private :
    T real,imag;
};
int main( )
{
    Complex<int> c1(3,4),c2(5,-10),c3; //定义对象时,用“类模板名<实际类型名>”形式
     cout<<"c1=";
    c1.display( );
    cout<<"c2=";
    c2.display( );
    c3=c1.complex_add(c2);
    cout<<"c1+c2=";
    c3.display( );
    c3=c1.complex_jian(c2);
    cout<<"c1-c2=";
    c3.display( );
    c3=c1.complex_cheng(c2);
    cout<<"c1*c2=";
    c3.display( );
    c3=c1.complex_chu(c2);
    cout<<"c1/c2=";
    c3.display( );
    cout<<endl;
    Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6; //定义对象时,用“类模板名<实际类型名>”形式
     cout<<"c4=";
    c4.display( );
    cout<<"c5=";
    c5.display( );
    c6=c4.complex_add(c5);
    cout<<"c4+c5=";
    c6.display( );
    c6=c4.complex_jian(c5);
    cout<<"c4-c5=";
    c6.display( );
    c6=c4.complex_cheng(c5);
    cout<<"c4*c5=";
    c6.display( );
    c6=c4.complex_chu(c5);
    cout<<"c4/c5=";
    c6.display( );
    return 0;
}
template<class T>
Complex<T>::Complex(T a,T b)
{
    real=a;
    imag=b;
}
template<class T>
Complex<T> Complex<T>::complex_add(Complex<T> &t)
{
    Complex c;
    c.real=real+t.real;
    c.imag=imag+t.imag;
    return c;
}
template<class T>
Complex<T> Complex<T>::complex_jian(Complex<T> &t)
{
    Complex c;
    c.real=real-t.real;
    c.imag=imag-t.imag;
    return c;
}
template<class T>
Complex<T> Complex<T>::complex_cheng(Complex<T> &t)
{
    Complex c;
    c.real=real*t.real;
    c.imag=imag*t.imag;
    return c;
}
template<class T>
Complex<T> Complex<T>::complex_chu(Complex<T> &t)
{
    Complex c;
    c.real=real/t.real;
    c.imag=imag/t.imag;
    return c;
}
template<class T>
void Complex<T>::display( )
{
    cout<<'('<<real<<','<<imag<<"i)"<<endl;
}

复数模板类_第1张图片

使用模板类时:

定义对象时,用“类模板名<实际类型名>”形式

每一个成员函数的定义前,必须要声明类模板  

你可能感兴趣的:(类,对象,Class)