我是模板的新手所以请原谅我天真的问题.我在这段代码中遇到错误:
template <class t>
class a{
public:
int i;
a(t& ii):i(ii){}
};
int main()
{
a *a1(new a(3));
cout<<a1.i;
_getch();
}
Run Code Online (Sandbox Code Playgroud)
编译错误:
'a' : use of class template requires template argument list'a' : class has no constructorsArm*_*yan 10
使用
a<int> *a1(new a<int>(3));
^^^^^ ^^^^
Run Code Online (Sandbox Code Playgroud)
如果希望自动推导出模板参数,可以使用辅助函数:
template<class T>
a<T> * createA (const T& arg) //please add const to your ctor, too.
{
return new a<T>(arg)
}
Run Code Online (Sandbox Code Playgroud)
a(t& ii):i(ii){}
Run Code Online (Sandbox Code Playgroud)
这应该是:
a(const t& ii):i(ii){}
Run Code Online (Sandbox Code Playgroud)
这样你就可以将const文字和临时文本传递给构造函数.
然后这样做:
a<int> *a1(new a<int>(3));
Run Code Online (Sandbox Code Playgroud)
你也可以写:
a<int> a2(3);
Run Code Online (Sandbox Code Playgroud)