简体   繁体   中英

C++ forward declarations with multiple classes, derived class

Currently I have 3 classes, set up like this:

World.h

include "WorldObject.h"
class WorldObject;
class TextObject; // when this is added, compiles fine, but tobj is incomplete when accessed 
//(world->tobj->function()).  if #include "TextObject.h" is added, numerous errors occur within TextObject.h
class World { 
public:
      WorldObject* wobj; // works fine
      TextObject* tobj; //trying to get this to be functional
};

WorldObject.h

#include "World.h"
class World;
class WorldObject {
public:
      WorldObject(World* world){...} // works fine, world can be accessed from world objects
};

TextObject.h

#include "WorldObject.h"
#include "World.h"
class TextObject : WorldObject {
public:
      TextObject(World* world) : WorldObject(w){...};
};

How can I use forward declaration so that tobj will be accessible from World.h, as obj is, with no errors? I am also using #pragma once at the beginning of each class. I have attempted to add "class World" to TextObject.h and "class TextObject" to World.h, but none of the seemingly standard procedures are working. Any suggestions?

#include <WorldObject.h> in your .cpp file rather than your header and you can access it from there.

Your header includes are causing circular dependencies, which you avoid through forward declarations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM