Cannot convert type to type* - C++ compile error

2020-05-03 13:58发布

问题:

I am trying to create a dynamic array of type 'T' that contains an array of type 'X'. In order to access attributes of T from X, I tried creating a pointer in struct X that points to T. This is the code I have:

struct WireSeg; // Forward declaration

struct Track { // Type X in above description
    int trackNum;
    bool used;
    WireSeg* parentWireSeg;
};

struct WireSeg { // Type T in above description
    int xCoord; 
    int yCoord;
    char flag;
    char orientation;
    Track* track;
};

typedef WireSeg* WireSegPtr

int main (void) {
  WireSegPtr wireSeg;
  wireSeg = new WireSeg[5];
  for (int i =0; i<5; i++) {
    wireSeg[i].track = new Track[3];
    for (int j =0; j<3; j++) {
      wireSeg[i].track[j].parentWireSeg = wireSeg[i];
    }
  }
}

I get the compile error:

error: cannot convert ‘WireSeg’ to ‘WireSeg*’ in assignment

I don't get it. parentWireSeg has been declared as a WireSeg type pointer and wireSeg[i] is also an element in the wireSeg array and is a pointer (isn't it?).

I tried playing around with it and declared parentWireSeg to be of type WireSeg:

struct Track {
    int trackNum;
    bool used;
    bool flag;
    WireSeg parentWireSeg;
};

This gave me error:

‘struct Track’ has no member named ‘parentWireSeg’.

This makes no sense to me either since struct Track does have parentWireSeg as an element! Can someone please explain this? Am I not allowed to have a pointer in Track that points to WireSeg?

I can probably use inherited classes (can I?) for this but I would prefer if someone told me what is wrong with my method?

回答1:

Try changing the line where you do the assignment to:

wireSeg[i].track[j].parentWireSeg = &wireSeg[i];

You see, wireSeg is of type WireSeg*, so when you dereference it by doing *wireSeg or wireSeg[0] or wireSeg[i], you get something that is of type WireSeg. If you want the address of the object instead of the object itself, so you can make a pointer, you need to add the address operator (&).



回答2:

wireSeg[i] is also an element in the wireSeg array and is a pointer (isn't it?).

No, wireSeg[i] is is a wireSeg, not a pointer to a wireSeg.

For instance, if you had an int foo[4] = {1, 2, 3, 4}, then foo[0] would be an int, not an int *, right?

You need &wireSeg[i] to get a pointer; or just wireSeg + i, as wireSeg can be treated as a pointer, and adding i is the same thing as getting the address of element i.