Can I make c++ code structure see each other? [duplicate]

强颜欢笑 提交于 2019-12-13 01:34:31

问题


Im not good at English.. sorry

for example,

struct structure1
{
   structure2 st;
}

struct structure2
{
   structure1 st;
}

It has incomplete type error

How can I use this code??

It is work well in java but in c++ I think because top down process..

I wonder It has solution good work

This is my real code

It is part of graph algorithm

struct Edge
{
    Node destination;

    int capacity;

    int cost;

    Edge dual;

    Edge(Node n, int c, int s)
    {
        capacity = c;

        cost = s;

        destination = n;

        dual.cost = -9999;
    }

};

struct Node
{
    int cost;

    vector<Edge> edges;

    Edge from;

    string name;

    bool onq;

    Node()
    {
        from.capacity = -9999;
    }

    void clear()
    {
        cost = 0;
        edges.clear();
        from.capacity = -9999;
    }
};

Thank you!!


回答1:


No you can't do this. It would be an endless recursion.

You could use a reference or a pointer though. See here how to do this:

struct structure2; // <<< forward declaration 
struct structure1
{
   structure2* st; // <<< use a pointer (or reference) 
   structure1(structure2* s2) : st(s2) {} // <<< initialize the pointer
};

struct structure2
{
   structure1 st;
   structure2() : st(this) {} // <<< pass the pointer
};

Live Demo



来源:https://stackoverflow.com/questions/37644151/can-i-make-c-code-structure-see-each-other

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!