普通函数的重载
普通函数重载很简单,只要参数不一样即可,如下:
void fun(){};
void fun(int a, int b){};
模板函数的重载
模板函数重载如下:
template<class T>
void test(T p1){
cout<<"test(T p1)"<<endl;
}
template<class T>
void test(T p1, T p2){
cout<<"test(T p1, T p2)"<<endl;
}
一个参数的模板类
不重载是没有问题的
template<typename T>
class A{
public:
T a;
A(T b){
b = a;
}
//类内函数
T getA(){
return a;
}
void setA(T c);
};
//类外定义函数,需要定义模板
template<typename T>
void A<T>::setA(T c){
}
int main(){
A<int> a(3);
a.setA(1);
int b = a.getA();
system("pause");
}
如果需要两个参数
template<typename T1, typename T2>
class A{
public:
T1 a;T2 b;
A(T1 c, T2 d){
a = c;
b = d;
}
};
如果这样编译会报错,因为和上面一个参数的类A是相同的类,C++认为这是一个类,那怎么解决这个问题呢?
使用#define,重复包含。通常我们每新建一个头文件,都在头文件中加入如下语句,防止重复包含:
#ifndef XXX_H
#define XXX_H
.......
#endif //XXX_H
现在,我们不加入上面这些,让它重复包含。建两个文件,一个是define.h解决多重参数的,一个是CA.h类文件。
CA.h代码如下:
#define COMBINE(a, b) COMBINE1(a, b)
#define COMBINE1(a, b) a##b
#define CLASS_NAME COMBINE(A, DELEGATE_SUFFIX)
DELEGATE_TEMPLATE DELEGATE_TEMPLATE_PARAMS
class CLASS_NAME{
public:
CLASS_NAME(DELEGATE_PARAMS){
cout<<"111"<<endl;
}
};
#undef COMBINE
#undef COMBINE1
#undef CLASS_NAME
#undef DELEGATE_SUFFIX
#undef DELEGATE_TEMPLATE
#undef DELEGATE_TEMPLATE_PARAMS
#undef DELEGATE_PARAMS
define.h代码如下:
#ifndef __DEFINE_H__
#define __DEFINE_H__
//定义一个参数
#define DELEGATE_SUFFIX 1
#define DELEGATE_TEMPLATE template
#define DELEGATE_TEMPLATE_PARAMS <typename TP1>
#define DELEGATE_PARAMS TP1 p1
#include "CA.h"
//定义两个参数
#define DELEGATE_SUFFIX 2
#define DELEGATE_TEMPLATE template
#define DELEGATE_TEMPLATE_PARAMS <typename TP1, typename TP2>
#define DELEGATE_PARAMS TP1 p1, TP2 p2
#include "CA.h"
#endif //__DEFINE_H__
调用如下:
#include <iostream>
#include <Windows.h>
#include "define.h"
using namespace std;
int main(){
A1<int> a(3);
A2<int ,double> b(3,4.0);
system("pause");
}
怎么样,简单吧……