C++: File header not recognizing class

Asked

Viewed 96 times

2

I am working with several classes, and to organize myself better, I put each class in a different file.

actor. h

#ifndef ACTOR_H
#define ACTOR_H

#include "SDL.h"
#include <string>

#include "collision.h"
#include "world.h"

class Actor
{
    (...)
};

world. h

#ifndef WORLD_H
#define WORLD_H

#include "actor.h"

class World
{
public:
    (...)
    Actor* getActor(std::string id); //Erro aqui
    (...)
};

But I’m getting the following error:

C:\Users\Felipe\Desktop\Joguinho v2\source\world.h|38|error: 'Actor' does not name a type|

Does anyone have any idea why the mistake was made?

  • Actor and World need to see each other? I’m just seeing dependence on World.getActor

  • 1

    Yes. There are several roles in Actor that use World class getters and setters

  • adapted my answer

2 answers

3


In C has a concept called forward declaration. I know this concept for functions, where I can declare the existence of the function to, only at a later time, explain how is the implementation.

In C++, this concept applies to classes as well. That response in the international Stack Overflow deals precisely with your problem (cyclical dependency between classes) using class declaration as forward declaration. The original answer also provides many interesting details of how the compiler works, I will summarize here how to avoid these problems in a pragmatic way.

In order to be able to reference a class (as a pointer or reference), it must be declared before. For your case of actors in a world, we can put the classes of that semantic level in the same header and code files.

To use this way, do so in the header:

#ifndef WORLD_ACTORS_H
#define WORLD_ACTORS_H

class Actor; // apenas a forward declaration, sem implementação 
class World; // idem

// real código relativo à classe Actor 
class Actor {
    ...
}

class World {
    Actor* getActor(std::string id);
    ...
}

In the code file, just include the header described above and be happy.

If you want to continue using classes in separate files (which is fair), you need to declare the Actor class in the World header (with forward declaration); as Actor depends on World, also do the forward declaration world-class.

1

Start here: put a semicolon after the class declaration...All class statements need a semicolon at the end.

class Actor
{
   (...)
}; //<------------------------------------

Editing:

Ok, since the commas have been hit then you can now accept the answer posed by "@Jefferson Quesado" and use forward declarations, because the error is being caused by includes recursives:

actor. h

#include "world.h" // <---------------------------------

world. h

#include "actor.h" // <------------------------
  • Edited post. I forgot to put them here in the post, but my code has. This is not the mistake

Browser other questions tagged

You are not signed in. Login or sign up in order to post.