【问题标题】:Method not found: Templates, Virtual Methods, Inheritence, Polymorphism未找到方法:模板、虚拟方法、继承、多态性
【发布时间】:2013-08-21 21:44:01
【问题描述】:

我对 c++ 还很陌生,我似乎找不到其他人遇到过与我完全相同的问题。基本上,我试图有一个我从不直接实例化的抽象类和几个子类。此外,我试图在所有超/子类上保持一致的模板。这是我的源文件。我有 3 个实用程序文件和一个用于主要功能的 .cpp 文件。

abstract_matrix.h

#ifndef ABSTRACTMATRIX
#define ABSTRACTMATRIX

template<class T>
class DataMatrix {

 public:
  int numFeatures;
  int numPoints;

  T* data;
  T* classifications; 

  virtual void scale(T scalar) = 0;
};

#endif

这是我对该抽象类的子类声明,sparse_host_matrix.h

#ifndef SPARSEHOSTMATRIX
#define SPARSEHOSTMATRIX

#include <iostream>

template<class T>
class SparseHostMatrix : public DataMatrix<T> {

 public:

  void scale(T scalar);
};

#endif

这是这些功能的实现..

#include "sparse_host_matrix.h"
#include <iostream>


template<class T>
void SparseHostMatrix<T>::loadFromFile(char* filename) {
  std::cout << "Loading in sparseHostMatrix" << std::endl;
}

template<class T>
void SparseHostMatrix<T>::scale(T scalar) {
  std::cout << "Loading in sparseHostMatrix" << std::endl;
}

当我运行这个主函数时......

#include <iostream>

using namespace std;
#include "abstract_matrix.h"
#include "sparse_host_matrix.h"

int main() {
  DataMatrix<double> *myMat = new SparseHostMatrix<double>;
  myMat->scale(.5);
}

我得到错误 undefined reference to `SparseHostMatrix::scale(double)

对于大量的代码,我很抱歉,我很困惑,并且在此问题上停留了一段时间,没有成功找到 SO 或其他方面的解决方案。

【问题讨论】:

    标签: c++ templates inheritance polymorphism virtual-functions


    【解决方案1】:

    模板函数的实现必须在头部。您不能将其放在单独的源文件中。编译器需要在使用函数时查看函数的实际主体,并且知道实际的模板参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-09
      • 2011-10-05
      • 1970-01-01
      • 2011-11-28
      • 2014-12-08
      • 2016-09-28
      • 2011-12-19
      相关资源
      最近更新 更多