Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Accessing attribute of Object Pointer in C++


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A void* is a pointer to void. void is no type. It is the absense of a type. It has no member functions that you could call. A void* can point to any object and in past times there were some use cases of void* in user code. Not anymore. If you want a pointer to a node, that is node*.

Taking into account the comment on naming, using struct to reduce verbosity, and using in-class initializers and the member initializer list, because members are not initialized in the constructors body, your code can look like this:

#include <iostream>

struct Node {
    int data;
    int* nextnode = nullptr;  
    Node(int storedData) : data(storedData)
    {}
};    

int main() {
    Node node(45);
    Node* node_ptr = &node;
    int b = node_ptr->data;   
    std::cout << node_ptr << std::endl;
    std::cout << b << std::endl;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...