C++ 模板 - 错误:“<”标记之前的预期初始值设定项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20376913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ template - error: expected initializer before '<' token
提问by DukeOfMarmalade
I am trying to learn about templates, I want my class pair to be able to hold two objects of any type. I just want to provide an accessor function for obj1 now. But I get the following error when I try to complile:
我正在尝试了解模板,我希望我的类对能够容纳任何类型的两个对象。我现在只想为 obj1 提供一个访问器函数。但是当我尝试编译时出现以下错误:
error: expected initializer before '<' token
T1 pair<T1,T2>::getObj1()
My code is:
我的代码是:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
template <class T1, class T2>
class pair
{
public:
pair(const T1& t1, const T2& t2) : obj1(t1), obj2(t2){};
T1 getObj1();
private:
T1 obj1;
T2 obj2;
};
template <class T1, class T2>
T1 pair<T1,T2>::getObj1()
{
return obj1;
}
int main()
{
return 0;
}
回答by Davidbrcz
pair is name of a standard class and with the using namespace std, there is a collision.
pair 是标准类的名称,与using namespace std存在冲突。
Several solutions :
几种解决方案:
- Rename your class to something else.
- Dont use the using statement
- 将您的班级重命名为其他名称。
- 不要使用 using 语句

