您的位置:首页 > Web前端

Is the type of “pointer-to-member-function” different from “pointer-to-function”?

2015-12-17 04:16 495 查看

Is the type of “pointer-to-member-function” different from “pointer-to-function”?

Yep.

Consider the following function:

int f(char a, float b);

The type of this function is different depending on whether it is an ordinary function or a non-
static
memberfunction of some class:

Its type is “
int (*)(char,float)
” if an ordinary function
Its type is “
int (Fred::*)(char,float)
” if a non-
static
member function of
class
Fred

Note: if it’s a
static
member function of
class
Fred
, its type is the same as if it were an ordinary function:“
int (*)(char,float)
”.

example code:

#include <iostream>
#include <string>
using std::string;

class Foo{
public:
int f(string str){
std::cout<<"Foo::f()"<<std::endl;
return 1;
}
};

int main(int argc, char* argv[]){
int (Foo::*fptr) (string) = &Foo::f;
Foo obj;
(obj.*fptr)("str");//call: Foo::f() through an object
Foo* p=&obj;
(p->*fptr)("str");//call: Foo::f() through a pointer
}
#include <iostream>
#include <string>
using std::string;

class Foo{
public:
static int f(string str){
std::cout<<"Foo::f()"<<std::endl;
return 1;
}
};

int main(int argc, char* argv[]){
//int (Foo::*fptr) (string) = &Foo::f;//error
int (*fptr) (string) = &Foo::f;//correct
(*fptr)("str");//call Foo::f()
}


https://isocpp.org/wiki/faq/pointers-to-members

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: