2014-01-14 44 views
1

我有三個文件method.h,method.cpp,main.cpp中未定義參考類方法

method.h

#ifndef METHOD_H 
#define METHOD_H 

class method { 

public: 
     void printThisMethod(); 
private: 

}; 

#endif 

method.cpp

#include "method.h" 
inline void method::printThisMethod() { 
    //some methods done here 
} 

的main.cpp

#include <iostream> 
#include <string> 
#include "method.h" 

int main() { 
    method outputMethod; 
    outputMethod.printThisMethod; 
} 

我得到的錯誤,

undefined reference to method::printThisMethod. 

請幫助謝謝

+0

刪除inline關鍵字。 – sajas

+0

鏈接錯誤?你如何建立這個? – doctorlove

+0

如果我刪除它,我將有方法:: printThisMethod()的錯誤多重定義,因爲我在一些函數中使用了「printThisMethod」,除了主 – user3193812

回答

3

要麼刪除inline關鍵字,或移動定義到頁眉(保持inline )。

inline用於放寬一個定義規則以允許標題中的定義。但是,它也需要定義在每個使用它的翻譯單位,這往往需要定義在一個頭。

沒有inline,正常的連接規則適用,並且在一個翻譯單元中必須有一個單一的定義。如果您從現有代碼中刪除inline,那麼這就是您將要使用的。

(你還需要括號添加到函數調用,outputMethod.printThisMethod(),但想必你真正的代碼有他們,否則不會得到儘可能的鏈接錯誤。)

+0

如果我刪除它,我將有方法:: printThisMethod()的錯誤的多重定義,因爲我在一些函數中使用了「printThisMethod」,除了主 – user3193812

+0

@ user3193812:你不應該得到那個錯誤,因爲你只能將其定義在單個源文件中。 (除非你像做這個源代碼文件而不是頭文件那樣瘋狂 - 但是你的例子當然沒有這樣做)。 –

+0

但這就是我在netbeans輸出中看到的7.4 – user3193812

0

您需要更改

outputMethod.printThisMethod; 

outputMethod.printThisMethod(); 
+0

仍然出現錯誤 – user3193812

+0

也從method.cpp中刪除'inline'關鍵字。如果您想要使用內聯類成員,則必須將其放入標題中。 – tillaert