对引用方法的未定义引用

时间:2014-11-15 01:00:28

标签: c++ c++11

当尝试编译下面的代码时,我收到以下错误:

$ g++ -std=c++11 main.cpp src/matrix.cpp
/tmp/ccsVOKfQ.o: In function `main':
main.cpp:(.text+0x1b): undefined reference to `matrix<int>::matrix(unsigned int, int)'
main.cpp:(.text+0x2c): undefined reference to `matrix<int>::operator[](int)'
collect2: error: ld returned 1 exit status

据我所知,所有代码都包含正确,它在Visual Studio中运行良好,但出于某种原因拒绝在Linux上的GCC中编译,给出了上述错误。

我的代码:

的src / matrix.hpp:

#ifndef __matrix_hpp
#define __matrix_hpp
#include <vector>
#include "../lib/typedefs.hpp"

// abstraction layer on top of 2D vector
template <typename t>
class matrix {
private:
  std::vector<std::vector<t>> _mat;
  uint _size;
public:
  matrix(uint, t);
  std::vector<t> get_row(int);
  std::vector<t> get_column(int);
  std::vector<t>& operator[](int);
  matrix transpose();
};

#endif

的src / matrix.cpp:

#include "matrix.hpp"

template <typename t>
matrix<t>::matrix(uint size, t default_val) {
  _size = size;
  _mat = std::vector<std::vector<t>>(_size, std::vector<t>(_size, default_val));
}

template <typename t>
std::vector<t> matrix<t>::get_row(int row_number) {
  return _mat[row_number];
}

template <typename t>
std::vector<t> matrix<t>::get_column(int col_number) {
  std::vector<t> column;

  for (int r = 0; r < _size; r++)
    column.push_back(_mat[r][col_number]);

  return column;
}

// provided as alternative notation to get_row
template <typename t>
std::vector<t>& matrix<t>::operator[](int i) {
  return get_row(i);
}

main.cpp中:

#include <iostream>
#include <cstdio>
#include "src/matrix.hpp"

int main() {
  matrix<int> m(9, 0); // test constructor
  m[1][2] = 100; // test operator overload
  return 0;
}

如何解决此问题并使代码编译?

0 个答案:

没有答案