专业编程基础技术教程

网站首页 > 基础教程 正文

C++程序(使用类模板)(c++程序的基本模块)

ccvgpt 2024-08-03 12:31:04 基础教程 12 ℃

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

#include<cmath>

C++程序(使用类模板)(c++程序的基本模块)

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:

最近发表
标签列表