代码之家  ›  专栏  ›  技术社区  ›  Guilherme Salome

正在编译。h带。cpp在同一目录上使用g++,错误

  •  0
  • Guilherme Salome  · 技术社区  · 7 年前

    我正在学习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 defined ld: symbol(s) not found for architecture x86_64 .

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

    1 回复  |  直到 7 年前
        1
  •  4
  •   M.M    7 年前

    的主体 inline 函数应在函数的所有调用站点上可见。

    在设置中,需要将这两个内联定义从 matrix.cpp matrix.h ; 或使其非内联。