如何解决C ++错误:“类”的重新定义

问题描述

我是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.cppEntity.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标头取决于std::string,那里需要#include <string>标头,而不仅仅是在实现文件(Entity.cpp)中。不需要在这里使用this->或某些分号(;)。


如果我注释掉#include "Entity.h"文件中的Entity.cpp并引用Main.cpp中的源而不是Entity.h,这很奇怪,它将编译并运行正常

这是因为您可以在类中内联定义函数(而不是将其放入实现文件中)。您所做的是在类定义中实现所有它们,因此您不再需要实现文件。

换句话说,尽管您将其命名为Entity.cpp而不是.cpp,但您的.h看起来像是具有该类的完整实现的头文件。因此,如果包含该文件,它将起作用。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...