它被重新定义是因为你定义了它两次:
// 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;
}