例如:
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);
}
#endifgraph.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;发布于 2016-10-04 11:09:20
这个问题与你的私人结构无关。构造函数应该能够访问所有私有成员。
由于您混淆了结构名node和变量名head,所以出现了这个问题
此->节点->name= newName;//不正确
相反,你应该写:
this->head->name = *newName;发布于 2016-10-04 11:14:52
如果要访问类变量,则应调用
this->head->name = *newName;尽管您可以省略this->,所以下面的内容很好
head->name = *newName;其他几个注意事项:
string* newName是一个指针,因此您需要使用dereference运算符"*“(即head->name = *newName;而不是head->name = newName; )访问它的值。node* head是一个指针,当前您正在尝试访问未初始化的指针。您可能也需要类似于head = new node();的东西。发布于 2016-10-04 11:16:54
您的问题与私人访问无关。首先,添加;以结束类声明:
class graph
{
// ...
};然后,键入this->node->name,而node是类型。将这一行更改为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规则的文章。
https://stackoverflow.com/questions/39850634
复制相似问题