简体   繁体   English

如何使用对象的指针调用对象的成员函数?

[英]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. 我有一个具有公共成员函数的Node对象。 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: 这是Node类中的成员函数:

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: 为了防万一,.setMarked()函数如下所示:

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. 这就是为什么它不起作用的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 语法错误:使用指向对象的指针调用成员函数指针 - Syntax Error: Call Member Function Pointer using Pointer to Object 如何使用指向常量 object 的指针调用成员 function 指针? - How do I call a member function pointer using a pointer to a constant object? 获取指向对象成员函数的指针 - Get a pointer to object's member function 错误的 function 调用调用成员 function 指向 object 的指针 - Bad function call in calling member function pointer from pointer to an object 使用指针成员对象的指针成员作为函数的参数 - Using a pointer member of a pointer member object as the argument of a function 是否可以使用其指针和void对象指针来调用成员函数? - Is it possible to call a member function with its pointer and a void object pointer? C ++:在另一个派生类的对象的基本指针上调用(派生的)成员函数 - C++: call (derived's) member function on base pointer of a different derived class's object 如何在对象成员函数内重新分配`this`指针? - How to reassign `this` pointer inside object member function? C ++:在不同类的派生对象的基本指针上调用静态成员函数 - C++: call static member function on base pointer of different class's derived object 对 std::function object 的调用不匹配,它是指向成员 function 的指针 - No match for call to std::function object which is pointer to member function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM