gpt4 book ai didi

c++ - 通过 C++ 中的另一个结构成员访问结构

转载 作者:行者123 更新时间:2023-11-28 04:39:00 26 4
gpt4 key购买 nike

我正在尝试使用另一个结构访问一个结构。在下面的程序中,element 是 Node 的成员。在这一行“temp->element *e_temp;”,我无法将 Node 的“element”成员链接到“elements”结构对象。编译错误说“'e_temp' 未在此范围内声明”。我错过了什么?

#include <vector>
#include <cstdlib>
using namespace std;
typedef struct Elements
{
int data;
struct Elements *next;
}elements;

typedef struct Node
{
int sno;
elements *element;
struct Node *next;
}node;

void add(int sno, vector<int> a)
{
node *temp;
temp = new node;

temp->element *e_temp;
e_temp = new elements;


temp->sno = sno;
while(a.size())
{
temp->e_temp->data = a[0];
temp->e_temp = temp->e_temp->next;
a.erase(a.begin());
}
}


int main()
{
vector<int> a{1,2,3};
int sno = 1;
add(sno, a);
return 0;
}

最佳答案

如果你只是想声明一个本地你可以做 auto e_temp = new elements 但我认为你想要的是那行 temp->element = new elements; 然后跟进您的其余代码以引用 temp 的元素而不是 e_temp。

    temp->element->data = a[0];
temp->element = temp->element->next

此外,我会尝试改掉使用 new 的习惯,改用 std::shared_ptrstd::unique_ptr .

关于c++ - 通过 C++ 中的另一个结构成员访问结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50662771/

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