-2

我不断收到“类类型重新定义错误”。我在网上阅读了几个建议添加#prgma onceor #ifndef GBMAP_H&的解决方案#define GBMAP_H,但没有一个解决问题。因此,即使我剥离代码,我仍然会遇到问题。我有一个 GBMap.cpp

#include "GBMap.h"

class GBMap {

};

GBMap.h

#pragma once

#include<iostream>
#include<cstdlib>
using namespace std;

class GBMap {

};

为什么要重新定义 GBMap 类?

4

2 回答 2

3

您的文件GBMap.cpp包含该类的两个定义GBMap。一个是您直接编写的,另一个定义是您从文件 GBMap.h 中包含的。包含后,翻译单元如下所示:

#include<iostream>
#include<cstdlib>
using namespace std;

class GBMap {

};

class GBMap {

};

如您所见,该类显然有两个定义。

每个翻译单元的类定义可能不超过一个,因此会出现错误。解决方案:更改程序,使该类只有一个定义。

于 2020-02-29T23:15:56.097 回答
2

它被重新定义是因为你定义了它两次:

// You can think of this as a cut and paste of GBMap.h so there's now
// a definition of GBMap here
#include "GBMap.h"

// And now you have a 2nd one.
class GBMap {

};

典型的模式是这样的:

在 GMap.h 中:

// This makes sure that if GMap.h is #included twice (including
// transitively) that the compiler only reads it once so you don't
// get the multiple definition error.
#pragma once

#include<iostream>
#include<cstdlib>
using namespace std;

// Define the class in the .h file
class GBMap {
 public:
  // This is just an example method to show what goes in the .cpp
  // Note that this method is declared here (we know it exists) but
  // not defined (we don't know what code to run if it's called)
  void SayHi() const;

};

在 GBMap.cpp 中:

// Include the definition - do **not** define it again after this
// you now have essentially copied the definition from GMap.h here
#include "GMap.h"


// Now add the **definition** (not declaration) for one of the class's methods
void GBMap::SayHi() const {
   std::cout << "Hi!" << std::endl;
}
于 2020-02-29T23:16:46.857 回答