【发布时间】:2017-12-21 03:15:01
【问题描述】:
我正在学习 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 或使用 g++ test.cpp matrix.cpp 编译 test.cpp 文件时,我收到错误:warning: inline function 'Matrix::operator()' is not defined 和 ld: symbol(s) not found for architecture x86_64。
问题:什么失败了?我如何理解正在发生的事情?感谢您的帮助!
【问题讨论】:
-
在你放置的任何地方都去掉“inline”关键字。无论你认为它意味着什么,它都不是那个意思。
-
或者将函数实现移到标题中,例如
inline double& operator()(int i, int j) {return d[i*c+j];} -
@SamVarshavchik 我正在关注一本书,这就是我将它放在那里的原因。该书解释说:“(...) 运算符定义的主体在编译时插入到代码中。这使得生成的程序更大,但节省了函数调用所需的执行时间。”你认为这是造成问题的原因吗?我怎样才能更好地理解正在发生的事情?感谢您的帮助!
-
@GuilhermeSalomé 这本书是正确的,但是对于这项工作,调用者必须能够直接看到函数实现。所以在你的情况下,它需要在标题中。
-
无关:未来的错误可能涉及三法则。预先警告是预先准备好的,所以请阅读:stackoverflow.com/questions/4172722/what-is-the-rule-of-three。