2016-10-11 120 views
-3

注意:我已經徹底搜索過SO,並且發佈了針對其他類似問題的解決方案在這裏並不適合我。C++錯誤:重新定義類

我寫在C++我自己定製的「弦」類,和我encoutering以下錯誤編譯時:

./PyString.h:8:11: error: out-of-line declaration of 'PyString' does not match any declaration in 'PyString' PyString::PyString (char*); ^

./PyString.h:9:11: error: definition of implicitly declared destructor PyString::~PyString (void);

pystring.cpp:4:7: error: redefinition of 'PyString' class PyString {

對於第一和第二的錯誤,周圍的析構函數移動到類在cpp文件中定義本身不起作用。

至於第三個錯誤,我似乎無法解決它 - 我不重新定義類!

這裏是pystring.h

#ifndef PYSTRING_INCLUDED 
#define PYSTRING_INCLUDED 

class PyString { 
    char* string; 
}; 

PyString::PyString (char*); 
PyString::~PyString (void); 

#endif 

這裏是:

#include "PyString.h" 
#define NULL 0 

class PyString { 
    char* string = NULL; 
    public: 
    PyString(char inString) { 
     string = new char[inString]; 
    }; 

    ~PyString(void) { 
     delete string; 
    }; 
}; 

作爲參考,這裏是編譯輸出作爲截圖: Compiler output screenshot

任何幫助不勝感激。

+7

,我認爲你應該得到[一好的初學者書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)並重新開始,因爲它沒有太多在你顯示的源是正確的。 –

+1

查找* .cpp文件中定義的頭中定義的類的示例。 – juanchopanza

回答

2

您正在將您的類PyString定義在您的標題和您的cpp文件中,而且函數定義在其末尾不需要;
而且......你的函數原型需要在你的類聲明在頭:

pystring.h

class PyString { 
public: //ALWAYS indicate what is public/private/protected in your class 
    PyString (char* inString); 
    ~PyString(); // Don't put void when there's no parameter 

private: // All attributes are private 
    char* string; 
}; 

pystring.cpp

#include "PyString.h" 

PyString::PyString(char* inString) { 
    string = inString; // Avoid using new unless you're forced to 
} 

PyString::~PyString() { 
} 
+1

'PyString ::'不應該出現在類定義中(這是一個錯誤,但一些編譯器讓它通過)。另外你對「pystring.c」的建議是完全錯誤的 –

+0

該死的,今天我犯了很多錯誤......謝謝 – Treycos

+0

我把這兩個片段複製到單獨的文件中,但是說'PyString :: PyString'是一個額外的資格。另外,它還說有重新宣佈。 – techydesigner

0

哦,是的,你是! pystring.h包含

class PyString { 
    char* string; 
}; 

這是一類聲明。聲明PyString::PyString (char*);PyString::~PyString (void);需要在聲明中。

但是,您在中指定了其他功能,並且定義了其中一些類似的。這就是你的編譯器告訴你的。

通常,你完全定義在頭部中的class(即所有成員,和的成員函數的聲明)和實現在源文件該類的成員函數。

這裏的故事寓意:你不能真正的通過試錯學習C++。得到一本好書!

+0

它也是類*定義*。那就是問題所在!至少,標題中報告了問題。 – juanchopanza

+0

*完全聲明*您的意思是*完全定義*(類,而不是成員)。 – juanchopanza