gpt4 book ai didi

c++ - 尝试连接两种不同类型的结构以创建链表

转载 作者:行者123 更新时间:2023-11-28 05:05:43 25 4
gpt4 key购买 nike

我正在寻找一种方法来连接由不同结构创建的节点,以制作链表和类似的东西。我尝试了几种方法,但我做不到。你能帮帮我吗?

这是我的代码:

struct nodeA{
int somedata;
nodeA* next;
};

struct nodeB{
int someData;
nodeB* next;
nodeB* someAnotherNode;
};

int main(){

nodeA* A0 = new nodeA; //Just creating some nodes...
nodeA* A1 = new nodeA;
nodeA* A2 = new nodeA;

nodeB* B0 = new nodeB;

A0 -> next = A1; //I can connect these nodes
A1 -> next = A2; //in this way.

A2 -> next = B0; //but, I can't do that!

return 0;
}

最佳答案

使用类和 polymorphism :

class NodeA {
public:
int somedata;
NodeA* next;
};

class NodeB : public NodeA {
NodeB* someAnotherNode;
};

int main(){
NodeA* A0 = new NodeA; //Just creating some Nodes...
NodeA* A1 = new NodeA;
NodeA* A2 = new NodeA;

NodeB* B0 = new NodeB;

A0 -> next = A1; //I can connect these Nodes
A1 -> next = A2; //in this way.

A2 -> next = B0; //but, I *can* do that!

return 0;
}

关于c++ - 尝试连接两种不同类型的结构以创建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44852063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com