头文件中的空类声明?(Empty class declaration in header file? [duplicate])

可能重复: 什么是c ++中的前向声明?

我只是对这段代码在这个简单的例子中做了什么有疑问。 我查找了朋友类并了解它们是如何工作的,但我不明白顶层的类声明实际上在做什么(即机器人)。 这是否意味着Happy类可以使用Robot对象但是它们无法访问其私有部分,任何信息都将被欣赏。

#include <stdlib.h> #include <stdexcept> template <typename T> // What is this called when included class Robot; // is there a special name for defining a class in this way template <typename T> class Happy { friend class Joe<T>; friend class Robot<Happy<T> >; // ... };

Possible Duplicate: What is forward declaration in c++?

I just have a question about what a piece of code is doing in this simple example. I've looked up friend classes and understand how they work, but I don't understand what the class declaration at the top is actually doing (i.e. Robot). Does this just mean that the Happy class can use Robot objects but they can't access its private parts, any information would be appreciated.

#include <stdlib.h> #include <stdexcept> template <typename T> // What is this called when included class Robot; // is there a special name for defining a class in this way template <typename T> class Happy { friend class Joe<T>; friend class Robot<Happy<T> >; // ... };

最满意答案

这是一个前瞻性声明

它只是告诉编译器,稍后将定义名为Robot的类模板,并且它应该期望该定义。

在此期间(即,直到Robot正式定义),它允许程序员在代码中引用该类型。 在您给出的示例中,有必要将Robot声明为Happy类的friend 。 (谁选了这些名字?!)

这是避免循环依赖并最小化编译时间/开销的常见策略。

It's a forward declaration.

It's just there to inform the compiler that a class template named Robot will be defined later and that it should expect that definition.

In the meantime (i.e., until Robot is officially defined), it allows the programmer to refer to that type in the code. In the example you've given, it is necessary to declare Robot as a friend of the Happy class. (Who picked these names?!)

It's a common strategy to avoid circular dependencies and minimize compilation time/overhead.

更多推荐