网站群cms,安县移动网站建设,广州软件合作中心,dw网站建设教程【知识点】泛型编程#xff0c;是 C 的一种重要编程思想#xff0c;其利用的主要技术是模板。 C 提供两种模板机制#xff1a;函数模板#xff08;function template#xff09;和类模板#xff08;class template#xff09;。【算法代码#xff1a;函数模板】 ● 函数…【知识点】泛型编程是 C 的一种重要编程思想其利用的主要技术是模板。 C 提供两种模板机制函数模板function template和类模板class template。【算法代码函数模板】 ● 函数模板的使用方法与调用普通函数的方法一样。 ● 调用函数模板时会自动将模板参数 T 替换为指定的类型参数。
#include iostream
using namespace std;//function template
template class T
T imax(T x, T y) {if(xy) return x;else return y;
}int main() {int a,b;double da,db;coutPlease input two integers:;cinab;coutPlease input two decimals:;cindadb;coutThe maximum value of integers is imax(a,b).endl;coutThe maximum value of decimals is imax(da,db).endl;return 0;
}/*
in:
Please input two integers:12 6
Please input two decimals:2.7 1.2out:
The maximum value of integers is 12.
The maximum value of decimals is 2.7.
*/【算法代码类模板】 ● C 类模板是一种用于创建通用类的机制。 ● 类模板的实现和普通类类似。 ● 类模板实例化和函数模板实例化不同类模板实例化需在类模板名字后跟 实例化类型即必须显示实例化不能自动类型推导。也就是说调用类模板时不会自动将模板参数 T 替换为指定的类型参数。
#include bits/stdc.h
using namespace std;//class template,allow setting default parameters
templateclass T1,class T2int
class Person {public:T1 iName;T2 iAge;public:Person(T1 name,T2 age) {this-iNamename;this-iAgeage;}void showPerson() {coutname:this-iNameendl;coutage:this-iAgeendl;}
};int main() {Personstring,int p1(Son Goku,888);p1.showPerson();//Person p(Son Goku, 1000); //no using automatic type inferencePersonstring p2(Cho Hakkai,666);p2.showPerson();return 0;
}/*
name:Son Goku
age:888
name:Cho Hakkai
age:666
*/