#ifndef ClassTemplate_HH
#define ClassTemplate_HH
using std::cout;
using std::endl;
template<typename T1,typename T2>
class myClass{
private:
T1 I;
T2 J;
public:
myClass(T1 a, T2 b);//Constructor
void show();
};
//这是构造函数
//注意这些格式
template <typename T1,typename T2>
myClass<T1,T2>::myClass(T1 a,T2 b):I(a),J(b){}
//这是void show();
template <typename T1,typename T2>
void myClass<T1,T2>::show()
{
cout<<"I="<<I<<", J="<<J<<endl;
}
#endif
在上面的头文件中,{}
无法删除,为什么?它的目的是什么?
myClass<T1,T2>::myClass(T1 a,T2 b):I(a),J(b){}
下面是源文件:
#include <iostream>
#include "ClassTemplate.h"
using std::cout;
using std::endl;
int main()
{
myClass<int,int> class1(3,5);
class1.show();
myClass<int,char> class2(3,"a");
class2.show();
myClass<double,int> class3(2.9,10);
class3.show();
}
错误编译结果如下:
$ g++ ClassTemplate_Test.cpp
ClassTemplate_Test.cpp: In function ‘int main()’:
ClassTemplate_Test.cpp:12:36: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
ClassTemplate.h:20:1: error: initializing argument 2 of ‘myClass<T1, T2>::myClass(T1, T2) [with T1 = int, T2 = char]’ [-fpermissive]
如何解决?谢谢