提交 5b509c8c 编写于 作者: W wsb

模板类和模板函数的使用示范

上级 24b955e7
...@@ -3,4 +3,4 @@ project(cpp_17_template) ...@@ -3,4 +3,4 @@ project(cpp_17_template)
set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD 11)
add_executable(cpp_17_template main.cpp) add_executable(cpp_17_template main.cpp templateClass.cpp)
#include <iostream> #include <iostream>
#include "templateClass.cpp"
using namespace std;
//定义函数模板
template<typename T>
//这部分为函数模板申明的标准格式,其中的T可以随便叫一个其他的合法的名称
inline T sum(T a, T b) { //使用函数模板定义的类型到函数中,当实际调用时会根据实际的参数类型对占位符T进行替换。
return a + b;
}
int main() { int main() {
std::cout << "Hello, World!" << std::endl;
//使用模板函数
int SUM = sum(22, 33);
cout << SUM << endl;
//使用模板类
templateClass<double> tc; //指定类型为double
//调用模板类的方法
cout<<"两数之和为:"<<tc.sum(23.56,32)<<endl;
cout<<"面积为:"<<tc.area(55.98,79.898)<<endl;
return 0; return 0;
} }
//
// Created by 11010 on 2023/4/9.
//注意:模板的类和函数的申明与定义均放在.cpp文件中,不然找不到定义。
//
template<class T> //申明这一句之后,后面就可以使用这里的类型了
class templateClass {
public:
T sum(T a, T b); //定义模板函数: 计算两数之和
T area(T len,T width); //定义模板函数:计算面积
};
template<class T>
T templateClass<T>::sum(T a, T b) {
return a+b;
}
template<class T>
T templateClass<T>::area(T len, T width) {
return len*width;
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册