简体   繁体   English

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

[英]Accessing a structure through another structure member in C++

I'm trying to access a structure using another structure. 我正在尝试使用另一个结构访问一个结构。 From the below program, element is the member of Node. 在下面的程序中,element是Node的成员。 At this line " temp->element *e_temp; ", I couldn't link the "element" member of Node to the "elements" structure object. 在这一行“ temp-> element * e_temp; ”中,我无法将Node的“ element”成员链接到“ elements”结构对象。 compile error says "'e_temp' was not declared in this scope". 编译错误说“在此范围内未声明'e_temp'”。 What am I missing? 我想念什么?

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

If you're just looking to declare a local you can do auto e_temp = new elements but what i think you want is this for that line temp->element = new elements; 如果您只是想声明一个本地auto e_temp = new elements可以执行auto e_temp = new elements但是我认为您想要的是该行temp->element = new elements; and then follow up with the rest of your code to reference temp's element instead of e_temp. 然后继续执行其余代码,以引用temp的元素而不是e_temp。

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

Also, i'd try to get out the habit of using new and use std::shared_ptr and std::unique_ptr instead. 另外,我会尝试摆脱使用new的习惯,而改用std::shared_ptrstd::unique_ptr

The correct declaration for e_temp is e_temp的正确声明是

elements * e_temp;

but e_temp is not use of any part of your code. 但是e_temp不使用代码的任何部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM