1

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!!

  • As for your edits. It's pretty much the same principle as I have shown in my answer. You forward declare `Node` and use a pointer or reference for it in `Edge`. – πάντα ῥεῖ Jun 05 '16 at 17:32
  • Also `Edge dual;` won't work. I have no idea of it's purpose, but if you want to reference another `Edge` instance, again use a pointer or a reference. – πάντα ῥεῖ Jun 05 '16 at 17:41
  • By the way, the reason it works in Java, is because in Java, when you declare a variable of a class type, you are actually creating a reference (which is like a pointer in C++), not an actual object of that class. The actual object is created on the heap when you do, for example, `st = new structure1();` – Benjamin Lindley Jun 05 '16 at 17:54
  • I catch error and fix this :D thank you ~~ It time to go bed.. 3:30 am good luck today~ – Park Yeoung Jun Jun 05 '16 at 18:33

1 Answers1

2

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

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Thank you but I wonder confound this code that st are not same variable I revise my question to see my real code It work well in java but c++.. Thank you!! – Park Yeoung Jun Jun 05 '16 at 17:18
  • @ParkYeoungJun _" that st are not same variable"_ Well, one is a member of `structure1` and the other is a member of `structure2` that they have the same name doesn't make them related anyhow. – πάντα ῥεῖ Jun 05 '16 at 17:20
  • yes it is no relation that variables I revise my question can see my code thank's to get attention xD – Park Yeoung Jun Jun 05 '16 at 17:26