c++ - 如何解决 C++ 错误 : Redefinition of 'class'

标签 c++ class header definition redefinition

我是 C++ 编程的新手,并且有一个我无法弄清楚的编译器错误。任何帮助,将不胜感激。
这是构建日志:

C:\Dev\MemberTest\Entity.cpp|6|error: redefinition of 'class Entity::Entity'|
C:\Dev\MemberTest\Entity.h|6|error: previous definition of 'class Entity::Entity'|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
该程序有Main.cpp , Entity.hEntity.cpp (我只是在修补如何实现头文件和源文件)。
#include <iostream>
#include "Entity.h"

int main()
{

    Entity::Entity Person("Grant", true); //Create person and set membership

    std::cout << Person.getName() << " is a member: " << Person.getMembership() << std::endl;

    return 0;
}
#ifndef ENTITY_H_INCLUDED
#define ENTITY_H_INCLUDED

namespace Entity
{
class Entity
{

    private:
        std::string name;
        bool member;

    public: //Get, set, constructor calls for a bool and string.
        Entity(std::string y, bool x);
        bool getMembership();
        std::string getName();
        void setMembership(bool x);

};
}

#endif // ENTITY_H_INCLUDED
#include <string>
#include "Entity.h"

namespace Entity
{
class Entity
{
    private:
        std::string name;
        bool membership;

    public:
        Entity(std::string y, bool x):name(y),membership(x){}
        bool getMembership(){return this->membership;};
        std::string getName(){return this->name;};
        void setMembership(bool x){this->membership=x;};

};
}
我四处寻找解决方案,发现了这样的问题:error: redefinition of class但我看到的解决方案与我的程序无关,因为我已经在使用 #ifndef .
由于我不确定这里可能需要哪些其他信息:所有三个文件都在同一个文件夹中,并且该文件夹中没有其他源文件或头文件。奇怪的是,如果我注释掉 #include "Entity.h"Entity.cpp文件并引用 Main.cpp 中的源而不是 Entity.h它编译并运行良好。我正在使用 Code::Blocks 和 GCC 编译器进行编码。再次感谢任何帮助。

最佳答案

实现文件 ( Entity.cpp ) 不应再次包含类定义。相反,您编写非内联定义(“类外”):

#include <string>
#include "Entity.h"

namespace Entity
{

Entity::Entity(std::string y, bool x) : name(y), membership(x) {}
bool Entity::getMembership() { return membership; }
std::string Entity::getName() { return name; }
void Entity::setMembership(bool x) { membership = x; }

}
另请注意您的 Entity.h header 取决于 std::string这需要 #include <string>头在那里,而不仅仅是在实现文件中( Entity.cpp )。没有必要使用this->这里也没有一些分号( ; )。

Oddly enough if I comment out the #include "Entity.h" in the Entity.cpp file and reference the source in Main.cpp instead of Entity.h it compiles and runs fine


那是因为您可以在类中内联定义函数(而不是将它们放在实现文件中)。您所做的是在类定义中实现所有这些,因此您不再需要实现文件。
换句话说,您的 Entity.cpp看起来像一个包含类的完整实现的头文件,尽管你称它为 .cpp而不是 .h .因此,如果您包含该文件,它将起作用。

关于c++ - 如何解决 C++ 错误 : Redefinition of 'class' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63680949/

相关文章:

c++ - 在头文件中定义类是否正确?

c++ - 是否有显式实例化深层模板类的技巧?

c++ - 在派生类中作为模板实现的虚函数

javascript - 访问任意父类(super class)中声明的属性

java - 类的公共(public)成员如何在 Java 中造成严重破坏?

c - 具有许多数字的随机数组出现错误

c++ - 哪个更好,放在一起或分开一些成本?

c++ - 在多线程 C++ 中如何以及必须同步哪些数据

python - 使用 rml 更改 openerp 7 页眉/页脚

button - 在 ionic 中,当向后滑动时,导航栏变为空白