代码之家  ›  专栏  ›  技术社区  ›  orochi

将问题模板与返回链接

  •  1
  • orochi  · 技术社区  · 14 年前

    我在将方法的参数作为模板返回时遇到了一些问题,请看:

    // CTestClass.h
    template<class T> 
    class CTestClass 
    {
    public:
        T getNewValue();
    };
    
    // CTestClass.cpp
    template<class T> 
    T CTestClass<T>::getNewValue()
    {
        return 10; // just for tests I'm returning hard coded 10
    }
    
    // main.cpp
    int _tmain(int argc, _TCHAR* argv[])
    {
        CTestClass<int> s;
        int a = s.getNewValue();
        return 0;
    }
    

    我得到以下错误:

    错误LNK2019:未解析的外部符号“public:int\u thiscall CTestClass::getNewValue(void)”(?getNewValue@?$CTestClass@H@@QAEHXZ)在函数中引用

    1 回复  |  直到 14 年前
        1
  •  3
  •   James McNellis    14 年前

    你会想读C++常见问题解答 "Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?"

    CTestClass<T>::getNewValue() 在头文件中。