简体   繁体   中英

How to call a member function of an object using that object's pointer?

I have a Node object that has a public member function. When I have a pointer (or double pointer) in this case pointing to the original object, how do I call the member function?

Here is the member function in the Node class:

class Node {
public:
    ...
    int setMarked();
    ...
private:
    ...
    int marked;
    ...
};

And here is where I am trying to call that function:

Node **s;
s = &startNode; //startNode is the original pointer to the Node I want to "mark"
q.push(**s); //this is a little unrelated, but showing that it does work to push the original object onto the queue.
**s.setMarked(); //This is where I am getting the error and where most of the question lies.

And just in case it matters, the .setMarked() function looks like this:

int Node::setMarked() {
    marked = 1;
    return marked;
}

Dereference it twice first. Note that * binds less tightly than . or -> , so you need parens:

(**s).setMarked();

Or,

(*s)->setMarked();

In your original code, the compiler was seeing the equivalent of

**(s.setMarked());

which is why it wasn't working.

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