[英]Access struct members inside a class private members?
例如:
图
#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
}
main.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;
该问题与您的私有结构无关。 构造函数应该能够访问所有私有成员。
问题在于您将结构名称node
和变量名称head
混淆了:
this-> node-> name = newName; //不正确
相反,您应该写:
this->head->name = *newName;
如果要访问类变量,应调用
this->head->name = *newName;
尽管您可以忽略此- this->
所以以下内容很好
head->name = *newName;
其他一些注意事项:
string* newName
是一个指针,因此您需要使用取消引用运算符“ *”(即head->name = *newName;
而不是head->name = newName;
来访问其值) head->name = newName;
node* head
是一个指针,当前您正在尝试访问未初始化的指针。 您可能需要像head = new node();
类的东西head = new node();
也一样 您的问题与私人访问无关。 首先,添加;
结束您的课程声明:
class graph
{
// ...
};
然后,当node
是类型时,您键入this->node->name
。 将此行更改为this->head->name
。 注意,指针head
在这里未初始化。
然后, newName
的类型为string*
而this->head->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;
}
另外,请阅读3/5/0规则 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.