C++ 模板 - 错误 : expected initializer before '<' token

标签 c++ templates

我正在尝试学习模板,我希望我的类对能够容纳两个任何类型的对象。我现在只想为 obj1 提供一个访问器函数。但是当我尝试编译时出现以下错误:

error: expected initializer before '<' token
    T1 pair<T1,T2>::getObj1()

我的代码是:

#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;
}

最佳答案

pair 是标准类的名称,与 using namespace std 存在冲突。

几种解决方案:

  • 将您的类(class)重命名为其他名称。
  • 不要使用using语句

关于C++ 模板 - 错误 : expected initializer before '<' token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20376913/

相关文章:

具有不同模板参数值的模板结构的 C++ 访问 protected 成员

c++ - `static constexpr auto` 使用未命名枚举初始化的数据成员

c++ - boost 文本反序列化在 32 位 Windows 机器上崩溃

c++ - 如何以在Linux中编译后提供预处理的汇编文件和目标文件的方式编译c/cpp代码?

c# - 在 C# 中调用 C++ 导出的函数

c++ - 将空基类指针转换为子类指针?

c++ - 如何为 std::list 重载 std::remove ?

c++ - 无法使用重载运算符<<来打印对象的值

c++ - VB脚本与COM接口(interface)继承相关的查询

c++ - 未使用的函数能否根据 C++14 实例化具有副作用的变量模板?