Col*_*nic 1 c++ member-function-pointers this
AFAIK,在C++中,在同一个类的函数成员中调用另一个成员函数不应该需要"this"前缀,因为它是隐式的.但是,在使用函数指针的特定情况下,编译器需要它.仅当我通过func指针包含调用的"this"前缀时,以下代码才能正确编译 -
当使用函数指针时,编译器可以在它指向同一个类的成员函数时推断出它吗?
class FooBar
{
private:
int foo;
public:
FooBar()
{
foo = 100;
}
int GetDiff(int bar)
{
return abs(foo - bar);
}
typedef int(FooBar::*MyFuncPtr)(int);
void FooBar::Bar()
{
MyFuncPtr f = &FooBar::GetDiff;
(this->*f)(10);
GetDiff(10);
}
};
Run Code Online (Sandbox Code Playgroud)
这是必需的,因为成员函数指针(与函数指针不同)不受约束,您可以将它们与不同的对象一起使用.
(this->*f)(10);
(foo.*f)(10);
// etc.
Run Code Online (Sandbox Code Playgroud)