简体   繁体   English

成员结构的前向声明

[英]Forward declaration of member struct

I want to write such a code, but it doesn't work: 我想编写这样的代码,但是不起作用:

struct ast;
struct parser;

struct parser
{
    struct node
    {
        node *parent;
    };

    ast build_ast() //here we want to use object of ast tyoe
    {
        node *ret = new node;
        return ast(ret);
    }
}; 

struct ast
{
    parser::node *root; //here we try to access member struct of y
    ast(parser::node *rt):root(rt){}
};

The problem is that I try to create in parser an object of incomplete type. 问题是我尝试在解析器中创建不完整类型的对象。 If I swap implementations of structures, the problem is that I try to access member struct of incomplete type. 如果我交换结构的实现,则问题是我尝试访问不完整类型的成员struct。 Obviously, I can solve this problem, by making node an independent structure, but that seems bad, because I may want to have other node types in my program. 显然,我可以通过使节点具有独立的结构来解决此问题,但这似乎很糟糕,因为我可能希望程序中具有其他节点类型。 The question is: can I somehow make a forward declaration of node struct outside the parser struct? 问题是:我可以以某种方式在解析器结构之外对节点结构进行前向声明吗? For example: 例如:

struct ast;
struct parser;
struct parser::node; //making a forward declaration of member struct

If this cannot be done, what are the ways to solve the conflict? 如果无法做到这一点,解决冲突的方法是什么?

You have to defer the definition of build_ast until ast is a complete type: 您必须推迟build_ast的定义,直到ast是一个完整类型:

inline ast build_ast(); //here we want to use object of ast type

inline is here to make this declaration functionally identical to what you had in example. inline是为了使此声明在功能上与示例相同。 You may want to remove it and move build_ast to an implementation file 您可能要删除它,并将build_ast移至实现文件

Outside of the struct definition: 在结构定义之外:

ast parser::build_ast()
{
    node *ret = new node;
    return ast(ret);
}

To forward-declare node , you need to do this within parser definition. 要转发声明node ,您需要在parser定义中执行此操作。 In other words, you cannot forward-declare an inner class without defining the outer. 换句话说,如果不定义外部类,则不能向前声明内部类。

struct parser
{
    struct node;
    // ...
};

You can then proceed with a definition: 然后,您可以继续进行定义:

struct parser::node
{
    node *parent;
};

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

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