繁体   English   中英

这份声明的目的和意义是什么

[英]What's the purpose and meaning of this declaration

我有这段代码,我正在查看下面的代码,但我无法弄清楚为什么class Node; 将被编写,然后再次但与实施。

class Doubly_Linked_List
{
   class Node; // <--- Why is this declared here??
   
   class Node : public Link {
        // Some Node code goes here.
   }
   
   Link head;
}

class Node; 是前向声明。 如果您想对不需要完整声明的 class 执行一些基本操作,它们有时会很有用。


这种基本操作的一个例子是方法的声明。 假设您的Doubly_Linked_List class 中有一堆非常重要的方法,并且您希望它们的声明靠近顶部。 因为有些方法在它们的声明中提到了Node ,所以你需要对Node进行某种声明——前向声明很好,因为它不会分散你对真正重要的东西——你的方法的注意力。

要定义您的方法,您必须为Node提供一个定义,但您稍后会在代码中进行定义,这有助于以一种合乎逻辑的方式组织它 - 首先是最重要的东西。

class Doubly_Linked_List
{
public:
   class Node; // forward declaration
   int very_important_method_1(Node node1, Node node2);
   Node very_important_method_2();

   // a virtual code separator; all code below is less important

   class Node : public Link {
        // Some Node code goes here.
   }
   
private:
   Link head;
}

int Doubly_Linked_List::very_important_method_1(Node node1, Node node2)
{
   // code
}

Doubly_Linked_List::Node Doubly_Linked_List::very_important_method_2()
{
   // code
}

这是一种利基技术; 如果您在前向声明后不久定义 class,则很少有用。


当 class 的定义在另一个文件中时,前向声明通常很有用。

您可以将代码分成两个文件,接口和实现。 Node的定义不属于接口文件(*.h),但需要声明部分Doubly_Linked_List class。 这是前向声明的经典用法。

// Doubly_Linked_List.h
class Doubly_Linked_List
{
public:
   class Node;
   int very_important_method_1(Node node1, Node node2);
   Node very_important_method_2();
   
   Node* whatever; // pointers to incomplete type are allowed here
}
// Doubly_Linked_List.cpp
class Node : public Link {
    // Some Node code goes here.
}

int Doubly_Linked_List::very_important_method_1(Node node1, Node node2)
{
   // code
}

Doubly_Linked_List::Node Doubly_Linked_List::very_important_method_2()
{
   // code
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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