2017-12-21 12 views
0

私はC++を学んでおり、.hファイルのクラス宣言と.cppファイルの定義があります。同じディレクトリでg ++を使用して.hpを.cppでコンパイルするとエラー

// 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]; 
} 

とテストファイルは次のように.hファイルがある

// 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

質問:何を失敗していますか?何が起こっているのかを私はどのように理解できますか?助けてくれてありがとう!

+2

「インライン」のキーワードをどこに置いても取り除くことができます。それが意味するものは何でも、それを意味するものではありません。 –

+0

こと、またはインライン)(ダブル・オペレータ(INTは、整数jをI){リターンdは[Iは、C + jを*];} 'のように、ヘッダに機能の実装を移動' – zzxyz

+0

@SamVarshavchik私は本以下午前、それが理由です私はそこにそれを持っています。 「(...)演算子定義の本体がコンパイル中にコードに挿入されるため、結果的にプログラムが大きくなりますが、関数呼び出しに必要な実行時間が節約されます。それが問題を引き起こしていると思いますか?何がうまくいっているのか、どうすれば理解できますか?助けてくれてありがとう! –

答えて

4

inline機能の本体は、機能の全てcallsitesで可視であるべきです。お使いの設定では

あなたは matrix.cppから matrix.hにそれらの2つのインライン定義を移動する必要があります。それらを非インラインにすることができます。

関連する問題