C ++:编译一些代码所需的转发类定义(C++: Forward class definition required to compile some code)

编程入门 行业动态 更新时间:2024-10-14 18:13:44
C ++:编译一些代码所需的转发类定义(C++: Forward class definition required to compile some code)

我正在用C ++编写一个小游戏作为练习,我遇到了一个难题。 基本思想是Level有一个Entity vector ,每个Entity实例知道它属于哪个级别。 到目前为止非常简单。

我在我的Entity类中得到了一些讨厌的编译错误,因为它无法弄清楚Level是什么。 在Entity 声明之前的一个简单的前瞻性声明容易修复。 但是,我已经在"Entity.h"包含了"Entity.h" 。 并且Level和Entity都在同一名称空间中声明和定义。

注意: Entity.h还包括Level.h 。

#include "Level.h" namespace GameNS { // Required, otherwise the compiler complains class Level; class Entity { public: ...

当它到达Entity时,编译器是否应该已经知道什么是Level ?

I am programming a small game in C++ as an exercise, and I've come across a conundrum. The basic idea is that a Level has a vector of Entity, and each Entity instance knows which level it belongs to. Pretty straightforward so far.

I was getting some nasty compile errors in my Entity class as it couldn't figure out what Level was. A simple forward class declaration right before the declaration of Entity easily fixed that. However, I am already including "Level.h" in "Entity.h". And Level and Entity are both declared and defined in the same namespace.

Note: Entity.h also includes Level.h.

#include "Level.h" namespace GameNS { // Required, otherwise the compiler complains class Level; class Entity { public: ...

Shouldn't the compiler already know what Level is, by the time it reaches Entity?

最满意答案

不,这不是C ++编译器的工作原理。 它的作用是它基本上一次传递一个翻译单元的文件。 宽松地说,TU是一个包含所有包含的实现文件。

如果你在Level.h和Entity.h包含了守卫(你可能会这样做)并且它们互相包含,其中一个,根据顺序,将被编译器遗漏,其中一个名称将不会声明。

根据经验,尽可能使用前向声明,并在必要时include s。

No, that's not how the C++ compiler works. What it does is it basically passes through the files one translation unit at a time. A TU is, loosely put, an implementation file with all its includes.

If you have include guards in Level.h and Entity.h (you probably do) and they include each other, one of them, depending on the order, will be left out by the compiler, and one of the names won't be declared.

As a rule of thumb, use forward-declarations when you can, and includes where you must.

更多推荐

本文发布于:2023-08-01 23:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1365825.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:所需   定义   代码   class   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!