C++ 在C+中使用模板+;
我正在尝试在类中执行泛型方法,现在,我有如下内容:C++ 在C+中使用模板+;,c++,templates,generics,C++,Templates,Generics,我正在尝试在类中执行泛型方法,现在,我有如下内容: #include "stdafx.h" #include <sstream> #include <iostream> #include <conio.h> using namespace std; class Test { public: template<class T> T returnVal(T value); } template<class T> T
#include "stdafx.h"
#include <sstream>
#include <iostream>
#include <conio.h>
using namespace std;
class Test
{
public:
template<class T>
T returnVal(T value);
}
template<class T>
T Test::returnVal(T value)
{
return value;
}
int main()
{
string reference = "stringVal";
Test ref;
cout << ref.returnVal<string>(reference);
getch();
return 0;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
课堂测试
{
公众:
模板
T返回值(T值);
}
模板
T测试::返回值(T值)
{
返回值;
}
int main()
{
string reference=“stringVal”;
试验参考;
cout''模板以下编译和运行符合预期:
#include <iostream>
using namespace std;
struct Test
{
template<class T>
T returnVal(T value);
};
template<class T>
T Test::returnVal(T value)
{
return value;
};
int main()
{
string reference = "stringVal";
Test ref;
cout << ref.returnVal<string>(reference);
return 0;
}
#包括
使用名称空间std;
结构测试
{
模板
T返回值(T值);
};
模板
T测试::返回值(T值)
{
返回值;
};
int main()
{
string reference=“stringVal”;
试验参考;
难道你漏掉了一个分号
只需在类定义之后添加一个;
class Test
{
...
};
^
|
+---- HERE
您的代码太不完整(缺少include、类定义后缺少分号等)如果没有其他错误,returnVal
是private
,您不能从类外调用它。另外,也不要忘记将函数设置为public
。如果显式使用泛型函数,它能工作吗?ref.returnVal(参考);@Deniseskimore:不应该,因为returnVal
的定义是错误的(应该是template t Test::returnVal(t value)
或类似的)。我重复一遍:在类定义后缺少分号。