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

问题描述 投票:0回答:1

我正在学习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;
}

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

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

c++ c++11 g++
1个回答
4
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.