开发者

Multiple class names inside single .hpp file

开发者 https://www.devze.com 2023-02-14 03:39 出处:网络
I\'m just beginning with C++, so I\'m looking some code to learn. I found this code fragment in a Breakout game.

I'm just beginning with C++, so I'm looking some code to learn. I found this code fragment in a Breakout game.

    #pragma once
    #include "force.hpp"
    #include "brick.hpp"
    #include <vector>

    class Painter;
    class Ball;

    class Wall
    {
    public:
      enum { ROWS_COUNT = 16,
         COLS_COUNT = 8 * 3 };
      enum { WIDTH = ROWS_COUNT * Brick::WIDTH,
         HEIGHT = COLS_COUNT * Brick::HEIGHT };
      Wall();
      void draw(Painte开发者_StackOverflowr &) const;
      Force tick(const Ball &);
    public:
      typedef std::vector<Brick> Bricks;
      Bricks bricks_;
    };

The only part that I don't understand is the following:

    class Painter;
    class Ball;

What's mean that two "class [name];"? In the source code there are differents Painter.cpp, Painter.hpp, Ball,hpp, Ball.cpp.

This mean some kind of include?


Those are forward declarations, which can be used to say that a name exists, but no definition of it exists at this time yet, but I want to use the name.

Note that in the class, it only uses pointers and references to Painter and Ball. When using forward declarations, this is completely fine, but if you put in code that depends on knowledge about the internals of the Painter or Ball classes (like calling a function or using a member variable of the class), then you'd have to include the actual class declarations.

For example, notice how the header #includes the brick.hpp header, because the class has an std::vector<Brick> container, that stores copies of Brick objects, and needs to know sizeof(Brick). The header also uses Brick::WIDTH and Brick::HEIGHT.

Another common use case for forward declarations is to fix the circular dependency problem.


That is called a forward declaration.


That just means "Expect there to be a Ball class and Painter class sometime in the future."


What you're looking at is something called forward declaration of types.

The short explanation is that this kind of thing speeds up compilation, because the compiler does not have to look at the header files where these types are declared, you just tell it that the types exist. This is possible as long as you don't need to know exactly the type or use any members. This is a good practice in header files.

This in only something you do in the header files. In .cpp files you need to include the headers where the types are declared, because here you'll most probably use the types and thus must know the real type and what it looks like.

0

精彩评论

暂无评论...
验证码 换一张
取 消