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

本文详细解释了C++中指针到成员函数与普通函数的区别,包括它们的类型、用法及实例代码演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值