简体   繁体   English

找不到方法:模板,虚方法,继承,多态

[英]Method not found: Templates, Virtual Methods, Inheritence, Polymorphism

I'm fairly new to c++ and I can't seem to find anyone else who has had the exact same problem as me. 我对c ++很新,我似乎找不到其他人和我有完全相同的问题。 Basically, I'm trying to have an abstract class which I never directly instantiate, and several child classes. 基本上,我正在尝试一个我从不直接实例化的抽象类,以及几个子类。 Also, I'm trying to keep a consistent template over all super/sub classes. 此外,我正在尝试在所有超级/子类上保持一致的模板。 Here's my source files. 这是我的源文件。 I have 3 utility files and one .cpp file for the main function. 我有3个实用程序文件和一个主函数的.cpp文件。

abstract_matrix.h 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

Here's my subclass declaration of that abstract class, sparse_host_matrix.h 这是我的抽象类sparse_host_matrix.h的子类声明

#ifndef SPARSEHOSTMATRIX
#define SPARSEHOSTMATRIX

#include <iostream>

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

 public:

  void scale(T scalar);
};

#endif

And here's the implementation of those functions.. 这是这些功能的实现..

#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;
}

And when I run this main function... 当我运行这个主要功能时......

#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);
}

I get the error undefined reference to `SparseHostMatrix::scale(double) 我得到错误未定义的引用`SparseHostMatrix :: scale(double)

Sorry for the massive amount of code, I'm just pretty confused and have been stuck on this for a while without successfully finding a solution on SO or otherwise. 对于大量的代码感到抱歉,我只是很困惑,并且已经坚持了一段时间没有成功找到SO或其他方面的解决方案。

Implementation of template functions must be in the header. 模板函数的实现必须在标题中。 You cannot place it in a separate source file. 您不能将其放在单独的源文件中。 The compiler needs to see the actual body of the function at the point where it is used and actual template parameters become known. 编译器需要在使用函数的位置查看函数的实际主体,并且实际模板参数已知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM