2012-11-20 58 views
0

這個星期,我開始升級我從C到C++的知識,我想重載一些運營商爲什麼我的班級沒有鏈接?

我稱之爲矩陣

#include "lcomatrix.h" 

inline Matrix::Matrix(unsigned rows, unsigned cols) : 
     rows_(rows), cols_(cols) 
{ 
     data_ = new double[rows * cols]; 
} 

inline Matrix::~Matrix() { 
    delete[] data_; 
} 

inline double& Matrix::operator()(unsigned row, unsigned col) { 
    return data_[cols_ * row + col]; 
} 

inline double Matrix::operator()(unsigned row, unsigned col) const { 
    return data_[cols_ * row + col]; 
} 
一類

lcomatrix.h內容是

#include <iostream> 

class Matrix { 
public: 
    Matrix(unsigned rows, unsigned cols); 
    double& operator()(unsigned row, unsigned col); 
    double operator()(unsigned row, unsigned col) const; 

    ~Matrix(); // Destructor   
    Matrix& operator=(Matrix const& m); // Assignment operator  

private: 
    unsigned rows_, cols_; 
    double* data_; 
}; 

Main.cpp

#include "lcomatrix.h" 
#include <iostream> 


/*- 
* Application entry point. 
*/ 
int main(void) { 

    Matrix mx(12,12); 

    //std::cout << mx << std::endl; 

    return 0; 
} 

Make文件:

CPPFLAGS=-I /path/lcomatrix/ 
EFLAGS= 

all : main.o lcomatrix.o 
    g++ $(EFLAGS) -o main.out main.o lcomatrix.o 

main.o: lcomatrix.o 
    g++ $(EFLAGS) $(CPPFLAGS) -c main.cpp 

lcomatrix.o: 
    g++ $(EFLAGS) -c /home/robu/UbuntuOne/ChibiOS-RPi/lcomatrix/lcomatrix.cpp 

clean: 
    rm *.o main.out 

當我嘗試建立我收到下面的鏈接錯誤:

make all 
g++ -c /home/robu/UbuntuOne/ChibiOS-RPi/lcomatrix/lcomatrix.cpp 
g++ -I /home/robu/UbuntuOne/ChibiOS-RPi/lcomatrix/ -c main.cpp 
g++ -o main.out main.o lcomatrix.o 
main.o: In function `main': 
main.cpp:(.text+0x1b): undefined reference to `Matrix::Matrix(unsigned int, unsigned int)' 
main.cpp:(.text+0x2c): undefined reference to `Matrix::~Matrix()' 
collect2: error: ld returned 1 exit status 
make: *** [all] Error 1 

我想這是一個非常愚蠢的錯誤,但作爲一個初學者我無法找出解決方案。

+5

沒有「升級」。你要麼學習正確的C++,要麼永遠註定要寫出可怕的C型怪物。 –

+3

取代'雙* data_中的數據;''與標準::矢量 data_','data_中的數據=新雙[行×COLS];''與data_.resize(0,行×COLS);',你會無不再需要'刪除[] data_' – andre

+0

根據本主題的矢量比陣列http://stackoverflow.com/questions/3664272/stdvector-is-so-much-slower-than-plain-arrays –

回答

5

你的方法定義都inline。爲了內聯函數,編譯器需要在編譯使用它的代碼時查看它的定義。

要麼把函數定義的地方,他們可以在使用的時候可以看出 - 在頭,或在Main.cpp的執行#included另一個文件 - 或者不將它們標記爲內聯。

相關問題