您的位置:首页 > 编程语言 > C语言/C++

C++ 模板->模板函数

2014-04-04 10:53 351 查看
类模板:

(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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: