使用.cpp使用G 在同一目录上使用.CPP,错误

Compiling .h with .cpp using g++ on the same directory, error

本文关键字:使用 CPP 错误 cpp      更新时间:2023-10-16

我正在学习C ,并且在.h文件中有类声明,并且在.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;
}

问题:当我使用g++ test.cpp编译test.cpp文件或使用g++ test.cpp matrix.cpp时,我会得到错误:warning: inline function 'Matrix::operator()' is not definedld: symbol(s) not found for architecture x86_64

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

inline函数的主体应在该函数的所有呼叫中可见。

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