【问题标题】:Access struct members inside a class private members?访问类私有成员中的结构成员?
【发布时间】:2023-03-22 13:09:01
【问题描述】:

例如:

graph.h

#ifndef GRAPH_H
#define GRAPH_H

#include <iostream>
#include <string>

using namespace std;

class graph
{
private:
    struct node
    {
        string name;
        int currentValue;
        struct node *next;
    };
    node* head;
public:
    graph();
    ~graph();

    graph(string* newName, int* givenValue);
}

#endif

graph.cpp

#include "graph.h"

graph::graph() {}

graph::~graph() {}

graph::graph(string* newName, int* givenValue)
{
    //This is what I want to achieve
    this->node->name = newName;                    //Compile error
}

ma​​in.cpp

#include "graph.h"
#include <iostream>

using namespace std;

int main()
{
    return 0; //Note I have not yet created a graph in main
}

如何访问上述函数的结构节点成员?

这是错误:

graph.cpp: In constructor ‘graph::graph(std::string*, double*)’:
graph.cpp:24:8: error: invalid use of ‘struct graph::node’
this->node->label = newName;

【问题讨论】:

  • 你要做的是:this-&gt;head-&gt;label = newName;; node 是一种类型,而不是成员数据。无论如何,我建议你不要使用指针,即:定义node head;而不是node* head;,然后使用this-&gt;head.label = newName;
  • 挑剔有时会有所帮助:您访问的不是结构/类的成员,而是结构/类实例的成员
  • 这是什么奇怪的图表,伙计?你确定你说的不是树?
  • this-&gt;head-&gt;name = *newName;

标签: c++ struct private-members


【解决方案1】:

您的问题与私人访问无关。首先,添加; 来结束你的类声明:

class graph
{
    // ...
};

然后,您输入了 this-&gt;node-&gt;namenode 是一个类型。将此行更改为this-&gt;head-&gt;name。注意这里指针head是未初始化的。

然后,newName 的类型为 string*,而 this-&gt;head-&gt;name 的类型为 string。根据你想如何使用你的类,你可以考虑像这样修改你的代码:

graph::graph(const string& newName, int givenValue):
    head(new node)
{
    //This is what I want to achieve
    this->head->name = newName;
}

或者像这样:

graph::graph(string* newName, int* givenValue):
    head(new node)
{
    //This is what I want to achieve
    this->head->name = *newName;
}

另外,阅读rule of 3/5/0

【讨论】:

    【解决方案2】:

    如果你想访问你应该调用的类变量

    this->head->name = *newName;
    

    虽然你可以省略this-&gt; 所以下面的就可以了

    head->name = *newName;
    

    其他几点说明:

    • string* newName 是一个指针,因此您需要使用取消引用运算符“*”访问它的值(即 head-&gt;name = *newName; 而不是 head-&gt;name = newName;
    • node* head 是一个指针,当前您正试图访问一个未初始化的指针。你可能还需要head = new node(); 之类的东西。

    【讨论】:

      【解决方案3】:

      问题与您的私有结构无关。构造函数应该能够访问所有私有成员。

      你混淆了结构名称node和变量名称head的问题:

      this->node->name = newName; // 不正确

      你应该写:

       this->head->name = *newName;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-31
        • 2013-01-09
        相关资源
        最近更新 更多