优秀的编程知识分享平台

网站首页 > 技术文章 正文

C++程序(使用类模板)(c++ 类使用)

nanyue 2024-07-25 06:02:55 技术文章 16 ℃

#include<iostream>//使用类模板实例

#include<cmath>

using namespace std;

template <typename T>

class Complex

{private:

T real;

T image;

public:

Complex(T x,T y)

{real=x;

image=y;

}

void show1()

{if(image<0)

cout<<real<<"-"<<abs(image)<<"i"<<endl;

else

cout<<real<<"+"<<image<<"i"<<endl;

}

void show2()

{if(image<0)

cout<<real<<"-"<<fabs(image)<<"i"<<endl;

else

cout<<real<<"+"<<image<<"i"<<endl;

}

};

int main()

{Complex<int> c1(3,-9),c2(6,7);

Complex<float> c3(4.78f,-5.69f),c4(2.55f,7.14f);

cout<<"c1=";c1.show1();

cout<<"c2=";c2.show1();

cout<<"c3=";c3.show2();

cout<<"c4=";c4.show2();

return 0;

}

C++源程序构成:

1、头文件;

2、命名空间;

3、声明模板:template<typename T>;

4、定义模板类;

5、主函数;

6、细节:在使用模板采取的样式为:类名<基本数据类型>对象.

Tags:

最近发表
标签列表