我是 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.h
和 Entity.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 theEntity.cpp
file and reference the source inMain.cpp
instead ofEntity.h
it compiles and runs fine
那是因为您可以在类中内联定义函数(而不是将它们放在实现文件中)。您所做的是在类定义中实现所有这些,因此您不再需要实现文件。
换句话说,您的
Entity.cpp
看起来像一个包含类的完整实现的头文件,尽管你称它为 .cpp
而不是 .h
.因此,如果您包含该文件,它将起作用。
关于c++ - 如何解决 C++ 错误 : Redefinition of 'class' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63680949/