使用g ++在同一目录下使用.cpp编译.h,错误

时间:2017-12-21 03:15:02

标签: c++ c++11 g++

我正在学习C ++,我在.h文件中有一个Class声明,在.cpp文件中有一个定义。 .h文件如下:

// matrix.h

class Matrix {
 private:
  int r; // number of rows
  int c; // number of columns
  double* d;
 public:
  Matrix(int nrows, int ncols, double ini = 0.0); // declaration of the constructor
  ~Matrix(); // declaration of the destructor
  inline double operator()(int i, int j) const;
  inline double& operator()(int i, int j);
};

.cpp是:

// matrix.cpp

#include "matrix.h"

Matrix::Matrix(int nrows, int ncols, double ini) {
  r = nrows;
  c = ncols;
  d = new double[nrows*ncols];
  for (int i = 0; i < nrows*ncols; i++) d[i] = ini;
}

Matrix::~Matrix() {
  delete[] d;
}

inline double Matrix::operator()(int i, int j) const {
  return d[i*c+j];
}

inline double& Matrix::operator()(int i, int j) {
  return d[i*c+j];
}

测试文件是:

// test.cpp
#include <iostream>
#include "matrix.h"

using namespace std;

int main(int argc, char *argv[]) {
  Matrix neo(2,2,1.0);
  cout << (neo(0,0) = 2.34) << endl;
  return EXIT_SUCCESS;
}

问题当我使用test.cpp或使用g++ test.cpp编译g++ test.cpp matrix.cpp文件时,我收到错误:warning: inline function 'Matrix::operator()' is not defined和{{ 1}}。

问题:失败的是什么?我怎么能理解发生了什么?谢谢你的帮助!

1 个答案:

答案 0 :(得分:4)

inline函数的主体应该在函数的所有调用中都可见。

在您的设置中,您需要将这两个内联定义从matrix.cpp移至matrix.h;或使它们非内联。