C++错误:重新定义类
注意:我已经彻底搜索过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;
};
};
任何帮助不胜感激。
您正在将您的类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() {
}
'PyString ::'不应该出现在类定义中(这是一个错误,但一些编译器让它通过)。另外你对“pystring.c”的建议是完全错误的 –
该死的,今天我犯了很多错误......谢谢 – Treycos
我把这两个片段复制到单独的文件中,但是说'PyString :: PyString'是一个额外的资格。另外,它还说有重新宣布。 – techydesigner
哦,是的,你是! pystring.h
包含
class PyString {
char* string;
};
这是一类声明。声明PyString::PyString (char*);
和PyString::~PyString (void);
需要在声明中。
但是,您在中指定了其他功能,并且定义了其中一些类似的。这就是你的编译器告诉你的。
通常,你完全定义在头部中的class
(即所有成员,和的成员函数的声明)和实现在源文件该类的成员函数。
这里的故事寓意:你不能真正的通过试错学习C++。得到一本好书!
它也是类*定义*。那就是问题所在!至少,标题中报告了问题。 – juanchopanza
*完全声明*您的意思是*完全定义*(类,而不是成员)。 – juanchopanza
,我认为你应该得到[一好的初学者书](http://*.com/questions/388242/the-definitive-c-book-guide-and-list)并重新开始,因为它没有太多在你显示的源是正确的。 –
查找* .cpp文件中定义的头中定义的类的示例。 – juanchopanza