2011-09-12 345 views
3

我有在C++仿製藥的問題,我有兩個Matrix.h和Matrix.cpp files.Here是文件:成員函數

#pragma once 
template<class T> 
class Matrix 
{ 
    public: 
     static T** addSub(int size,T** firstMatrix,T** secondMatrix,int operation); 
} 

和Matrix.cpp

#include "Martix.h" 
template<class T> 
static T** Matrix<T>::addSub(int n,T **firstMatrix,T **secondMatrix,int operation) 
{ 
    //variable for saving result operation 
    T **result = new T*[n]; 

    //create result matrix 
    for(int i=0;i<n;i++) 
     result[i] = new T[n]; 

    //calculate result 
    for(int i=0;i<n;i++) 
     for(int j=0;j<n;j++) 
      result[i][j] = 
      (operation == 1) ? firstMatrix[i][j] + secondMatrix[i][j]: 
           firstMatrix[i][j] - secondMatrix[i][j]; 

    return result; 
} 

當我運行這些我得到以下錯誤:

Error 1 error LNK2019: unresolved external symbol "public: static int * * __cdecl Matrix<int>::addSub(int,int * *,int * *,int)" ([email protected][email protected]@@[email protected]) referenced in function "public: static int * * __cdecl Matrix<int>::strassenMultiply(int,int * *,int * *)" ([email protected][email protected]@@[email protected]) C:\Users\ba.mehrabi\Desktop\Matrix\matrixMultiplication\main.obj matrixMultiplication 

是什麼問題?

+0

您是否在聲明的同一編譯單元中使用了模板方法定義? – Simone

+2

http://stackoverflow.com/questions/488959/how-do-you-create-a-static-template-member-function-that-performs-actions-on-a-te – Patrick

+0

你拼錯包括的名稱文件。我想知道你是否在這裏給我們提供真正的代碼,或者如果你只是從內存中寫下一些小說......另外,C++沒有「泛型」。如果您來自Java背景,那麼您可能會習慣於使用常見的C++習慣用法,這些習慣用法很不相同。例如,你應該很少或從不在C++中說'新'。 –

回答

5

不幸的是,你不能在* .cpp文件中聲明一個模板類。完整的定義必須保留在頭文件中。這是許多C++編譯器的規則。

看到這個:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12

  1. A template is not a class or a function. A template is a "pattern" that the compiler uses to generate a family of classes or functions.
  2. In order for the compiler to generate the code, it must see both the template definition (not just declaration) and the specific types/whatever used to "fill in" the template. For example, if you're trying to use a Foo, the compiler must see both the Foo template and the fact that you're trying to make a specific Foo.
  3. Your compiler probably doesn't remember the details of one .cpp file while it is compiling another .cpp file. It could, but most do not and if you are reading this FAQ, it almost definitely does not. BTW this is called the "separate compilation model."

鏈接有一個解決辦法,但要記住,模板是一個榮耀的宏,以便頭文件可能是它最好的地方。

this SO帖子顯示瞭解決方法的演示。

1

首先,類模板函數的定義應該放在頭本身。其次,如果你在類之外定義了static成員函數(儘管在頭本身中),那麼不要使用關鍵字static(在定義中)。它只需要在聲明中。

0

添加

template Matrix<int>; 

在你的CPP文件的末尾,它會工作。但是你需要學習一些關於模板的東西,否則你將不得不面對很多你不瞭解的問題。