简体   繁体   中英

Access struct members inside a class private members?

For Example:

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
}

main.cpp

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

using namespace std;

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

How can I access the struct node members for the function above?

This is the error:

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

The problem has nothing to do with your private struct. The constructor should be able to access all private members.

The problem as that you confused the struct name node and the variable name head :

this->node->name = newName; // incorrect

Instead you should write:

 this->head->name = *newName;

If you want to access the class variable you should call

this->head->name = *newName;

though you can omit this-> so the following is fine

head->name = *newName;

Couple of other notes:

  • string* newName is a pointer so you need to access its value with the dereference operator "*" (ie head->name = *newName; instead of head->name = newName;
  • node* head is a pointer and currently you are trying to access an uninitialized pointer. You probably need something like head = new node(); as well.

Your problem is not related to private access. First, add ; to end your class declaration:

class graph
{
    // ...
};

Then, you typed this->node->name while node is a type. Change this line for this->head->name . Note that the pointer head is uninitialized here.

And then, newName is of type string* while this->head->name is of type string . Depending on how you want to use your class, you may consider modifying your code like this:

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

Or like this:

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

Also, read about rule of 3/5/0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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