2011-09-12 153 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文件的末尾,它会工作。但是你需要学习一些关于模板的东西,否则你将不得不面对很多你不了解的问题。