C++ 错误 : redefinition of class

标签 c++ class compiler-errors g++

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

5年前关闭。




Improve this question




注:我已经对 SO 进行了彻底的搜索,并且为其他有类似问题的人发布的解决方案在这里对我不起作用。

我正在用 C++ 编写自己的自定义“类字符串”类,并且在编译时遇到以下错误:

./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

这里是 pystring.cpp :
#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

任何帮助是极大的赞赏。

最佳答案

您在 header 和 cpp 文件中定义类 PyString,而且,函数定义不需要 ;在它结束时。
而且...您的函数原型(prototype)需要在您的标题中的类声明中:

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() {
}

关于C++ 错误 : redefinition of class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39972087/

相关文章:

PHP:速记开关

c - 使用gmp编译时出错

c++ - 如何正确创建函数头而不出现多重定义错误?

c++ - 在 C++ 应用程序中构建/编译 libcurl 时遇到问题

c++ - 具有多种类型的类数组?如何访问数组中的一种类型?

c++ - 无法从 '_int64' 转换为 'Data *'

C++:元组列表 C++11/1y

java - URLClassLoader 究竟是如何工作的? java

c++ - 使用 std::make_unique 优于 new 运算符的优点

c++ - GetCurrentDirectory 并没有真正返回可执行文件的路径