2013-10-07 102 views
1

我是C++的新手,但我還不太瞭解。我有這個奇怪的問題。我有正常工作的功能,但是當我嘗試運行它作爲沒有任何改變一個類的成員函數,它不工作 它說: 未定義參考gsiread :: get_rows(字符*)函數編譯正確,但它不作爲類的成員函數編譯

#include <string> 
#include <vector> 
#include <fstream> 

using namespace std; 
//vector<string> get_rows (char filepath[]); ... it works 

class gsiread { 

     public: 
     vector<string> get_rows (char filepath[]); ... it doesnt work 

     private: 
     }; 

vector<string> get_rows (char filepath[]) { 

    vector<string> data; 
    string str; 

    ifstream file; 
    file.open(filepath); 

    if(file.is_open()) { 
     while(getline(file,str)) { 

     if (str.empty()) continue; 
     data.push_back(str); 

     } 
    } 
    return data; 
} 

// This part is "like" main i am using Qt creator and i have copied parts of code 
    from separate files 

gsiread obj; 

vector<string> vypis; 
vypis = obj.get_rows("ninja.txt"); ....... //This doesnt work 

vypis = get_rows("ninja.txt"); .......... //This works if I put declaration of 
              //function get_rows outside the class and 
              //and use // on declaration inside the class 

for(int i = 0; i < vypis.size(); i++) { 

    QString n = QString::fromStdString(vypis[i]); 

    QString t = "%1 \n"; 

    ui->plainTextEdit->insertPlainText(t.arg(n)); 


    // QString is like string but zou have to use it if wanna use widgets 
    // of qt (I think) 
} 

回答

2

通知。它將您的功能get_rows視爲與gsiread::get_rows完全不同的實體,並且出現鏈接器錯誤,因爲編譯器無法找到gsi::get_rows

嘗試改變這一閱讀

vector<string> gsiread::get_rows (char filepath[]) { 
    ... 
} 

更一般地,即使一個功能相同的源文件作爲類中定義,C++不會認爲它是類的一部分。你需要或者

  • 定義它的類體內,或
  • 與類名

明確前綴是爲了使功能的成員函數。

希望這會有所幫助!

+0

它幫了很多,謝謝。 :) – Rokusjar

2

如果你想get_rows是的gsiread一員,它的實現需要顯示此

vector<string> gsiread::get_rows(char filepath[]) { 
//    ^^^^^^^^^ 
+0

重點在_implementation_,而不是_declaration_ :) – xtofl

+0

非常感謝:)我真的讚賞它。 – Rokusjar

+0

不客氣。如果您的問題得到解答,您可以通過[接受](http://meta.stackexchange.com/q/5234)表明其中一個答案。 – simonc

1

當你定義的成員函數,你需要把它放在類範圍:

vector<string> gsiread::get_rows (char filepath[]) { .... } 
//    ^^^^^^^^^ 

否則,它被視爲非成員函數,並且您的成員函數被聲明但未定義,從而導致錯誤。您已經定義了功能

vector<string> get_rows (char filepath[]) { 
    ... 
} 

C++將此視爲一個免費的功能,而不是一個成員函數,因爲你沒有提到它屬於類