无法将类型转换为类型*-C ++编译错误 [英] Cannot convert type to type* - C++ compile error

查看:140
本文介绍了无法将类型转换为类型*-C ++编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个动态类型为 T的数组,其中包含一个类型为 X的数组。为了从X访问T的属性,我尝试在结构X中创建一个指向T的指针。这是我拥有的代码:

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];
    }
  }
}

我得到了编译错误:


错误:无法在分配中将'WireSeg'转换为'WireSeg *'

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

我不明白。 parentWireSeg 被声明为 WireSeg 类型指针和 wireSeg [i] 也是 wireSeg 数组中的一个元素,并且是一个指针(不是吗?)。

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?).

我尝试使用它,并声明 parentWireSeg 的类型为 WireSeg

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

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

这给了我错误:


'struct Track'没有名为'parentWireSeg'的成员。

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

这对我来说也没有意义,因为struct Track 确实具有 parentWireSeg 作为元素!有人可以解释一下吗?我是否不允许在 Track 中有一个指向 WireSeg 的指针?

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?

推荐答案

尝试将执行分配的行更改为:

Try changing the line where you do the assignment to:

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

您看到的是,wireSeg的类型为 WireSeg * ,因此当您通过执行 * wireSeg wireSeg [0] wireSeg取消引用它时[i] ,您得到的类型为 WireSeg 。如果您想要对象的地址而不是对象本身,那么可以创建一个指针,则需要添加地址运算符(&)。

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 (&).

这篇关于无法将类型转换为类型*-C ++编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆