C++ 模板->模板函数
2014-04-04 10:53
351 查看
类模板:
(1)对模板参数没有限制
(2)避免代码的重复
(3)注意重载的准确的匹配
(4)模板的组合技术(下一次用STL分析)
(1)对模板参数没有限制
(2)避免代码的重复
(3)注意重载的准确的匹配
(4)模板的组合技术(下一次用STL分析)
// #include "stdafx.h" //#include<iostreamstd::> #include "stdafx.h" #include <iostream> #include <string> #include <vector> using namespace std; vector<int> v; template <typename T>//加法函数模板 T Add(T x,T y) template <typename T>//在类模板定义之前,都需要加上模板声明 class BinaryOperation//二目运算类 { private: T x; T y; char op; void add() { std::cout<<x<<op<<y<<"="<<x+y<<std::endl; } void sub() { std::cout<<x<<op<<y<<"="<<x-y<<std::endl; } void mul(); void div(); public: BinaryOperation(T x,T y):x(x),y(y) { } void determineOp(char op); }; //在类外定义成员函数: //在成员函数定义之前进行模板声明, //且在成员函数名之前加上"类名<类型参数>::" template <typename T> void BinaryOperation <typename T>::mul() { std::cout<<x<<op<<y<<"="<<x*y<<std::endl; } template <typename T> void BinaryOperation <typename T>::div() { std::cout<<x<<op<<y<<"="<<x/y<<std::endl; } template <typename T> void BinaryOperation <typename T>::determineOp(char op) { this->op=op; switch(op) { case'+': add(); break; case'-': sub(); break; case'*': mul(); break; case'/': div(); break; default: break; } } int main() { BinaryOperation<double> op(12.5,14.6); op.determineOp('+'); op.determineOp('-'); op.determineOp('*'); op.determineOp('/'); system("pause"); return 0; } { return x+y; } int main() { int x=10,y=10; std::cout<<Add(x,y)<<std::endl;//相当于调用函数int Add(int,int) double x1=10.10,y1=10.10; std::cout<<Add(x1,y1)<<std::endl;//相当于调用函数double Add(double,double) long x2=9999,y2=9999; std::cout<<Add(x2,y2)<<std::endl;//相当于调用函数long Add(long,long) return 0; }
相关文章推荐
- C++ 模板->模板函数
- 比较C++中的4种类型转换方式
- C语言main()函数详解
- 使用C++的开源序列化(Serialization)库cereal
- 《Effective C++(第三版)》 的55条建议
- 在Eclipse中开发C/C++项目
- 快速排序和插入排序的C++实现
- c语言中const关键字详解
- 自底向上的归并排序-转自算法C语言实现
- 大学C语言老师不会告诉你的int main()
- c++强制类型转换:dynamic_cast、const_cast 、static_cast、reinterpret_cast
- c++强制类型转换:dynamic_cast、const_cast 、static_cast、reinterpret_cast
- C++中建立动态链接库及使用注意事项
- Code::Blocks手册 中文翻译版~
- C++ STL,ATL,WTL之间的联系和区别
- C++类的交叉引用问题
- c++中 string 类的find函数的用法
- C++错误:“__w64 unsigned int”的前面应有“;”
- C++ 中string.find() 函数的用法总结
- C++成员函数的 重载、隐藏、覆盖分析