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

模板使用中的编译错误

c++
  •  1
  • bjskishore123  · 技术社区  · 14 年前
    template <class T>
    class Test
    {
    public:
     template<class T>
     void f();  //If i define function here itself, error is not reported.
    };
    
    template <class T>
    void Test<T>::f() 
    {
    }              //Error here.
    
    int main()
    {
     Test<float> ob;
     ob.f<int>();
    }
    

    它产生以下错误。

    error C2244: 'Test<T>::f' : unable to match function definition to an
    existing declaration
    


    Error表示声明和定义具有相同的原型,但不匹配。 为什么这是个错误?怎么解决呢?

    如果我在类中定义函数,它不会报告错误。 但我想在课外定义。

    2 回复  |  直到 14 年前
        1
  •  2
  •   Chubsdad    14 年前

    更改为

    template <class T> 
    class Test 
    { 
    public: 
     template<class U> 
     void f(); 
    }; 
    
    template <class T> 
    template<class U>
    void Test<T>::f()  
    { 
    } 
    
        2
  •  1
  •   Prasoon Saurav    14 年前
    ....
    public:
      template<class T> // this shadows the previous declaration of typename T
       void f();  
    };
    

    更改参数名称。 Here