diff --git a/CMakeLists.txt b/CMakeLists.txt index b90d4b0e25f65664a2cd1b8287b3484b8d738a10..a1e907672c935ce87455952b9a86050c90a095b9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,4 +3,4 @@ project(cpp_17_template) set(CMAKE_CXX_STANDARD 11) -add_executable(cpp_17_template main.cpp) +add_executable(cpp_17_template main.cpp templateClass.cpp) diff --git a/main.cpp b/main.cpp index bc8f460d02aeb0695e7840121bc4caefe788a878..fbaf29747958bed3e254de1782ee00705fc169ae 100644 --- a/main.cpp +++ b/main.cpp @@ -1,6 +1,27 @@ #include +#include "templateClass.cpp" + +using namespace std; + +//定义函数模板 +template +//这部分为函数模板申明的标准格式,其中的T可以随便叫一个其他的合法的名称 +inline T sum(T a, T b) { //使用函数模板定义的类型到函数中,当实际调用时会根据实际的参数类型对占位符T进行替换。 + return a + b; +} + int main() { - std::cout << "Hello, World!" << std::endl; + + //使用模板函数 + int SUM = sum(22, 33); + cout << SUM << endl; + + //使用模板类 + templateClass tc; //指定类型为double + //调用模板类的方法 + cout<<"两数之和为:"< //申明这一句之后,后面就可以使用这里的类型了 +class templateClass { +public: + T sum(T a, T b); //定义模板函数: 计算两数之和 + T area(T len,T width); //定义模板函数:计算面积 + +}; + + +template +T templateClass::sum(T a, T b) { + return a+b; +} + +template +T templateClass::area(T len, T width) { + return len*width; +}