类成员函数指针作为类成员
// class
class MyClass
{
public:
void doIt() const
{
cout << "It works!" << endl;
}
void(MyClass::*fPtr)() const;
};
// main
MyClass *t = new MyClass;
// store function address
t->fPtr = &MyClass::doIt;
(*(t->fPtr))(); // Whats wrong with this line?
如何调用 fPtr 中存储的函数?当我尝试 (*(t->fPtr))();编译器给出 这些错误:
错误 C2171:'*':对类型为 'void (__thiscall MyClass::* )(void) const
错误 C2064 的操作数非法:术语不计算为采用 0 个参数的函数
// class
class MyClass
{
public:
void doIt() const
{
cout << "It works!" << endl;
}
void(MyClass::*fPtr)() const;
};
// main
MyClass *t = new MyClass;
// store function address
t->fPtr = &MyClass::doIt;
(*(t->fPtr))(); // Whats wrong with this line?
How can i call the function stored in fPtr? when i try (*(t->fPtr))(); compiler gives
those errors :
error C2171: '*' : illegal on operands of type 'void (__thiscall MyClass::* )(void) const
error C2064: term does not evaluate to a function taking 0 arguments
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(*(t->fPtr))();
是错误的,正确的语法是((object)->*(ptrToMember))
表示
更多背景信息这里:http://www.parashift.com/c++-faq-lite/pointers-to-members.html
(但最好忽略该页面中的这些宏..)
(*(t->fPtr))();
is wrong, thre right syntax is((object)->*(ptrToMember))
means
More background info here: http://www.parashift.com/c++-faq-lite/pointers-to-members.html
(But better ignore these macros from that page..)
main()
函数范围内没有名为fPtr
的变量。您需要使用->
运算符引用成员变量,然后使用->*
取消引用指向成员的指针:或者,您可以创建一个局部变量并分配指向它的成员的指针:
后者清楚地说明了为什么需要上面看起来奇怪的构造。您还可以对与您使用的指针成员类型的成员变量不同的对象执行方法:
->
左侧的对象告诉编译器要读取哪个对象while->*
左侧的对象告诉编译器要在哪个对象上调用成员函数。There is no variable called
fPtr
in the scope of themain()
function. You need to refer to the member variable using->
operator and then dereference pointer-to-member using->*
:Alternatively you can create a local variable and assign the pointer-to-member to it:
The latter makes it clear why the strange-looking construct above is needed. You can also execute a method on an object different from the one whose member variable of pointer-to-member type you use:
The object on the left of
->
tells the compiler which object to read the pointer-to-member from while the object on the left of->*
tells the compiler which object to call the member function on.