C++成员函数指针

来源:互联网 发布:三星ml1641清零软件 编辑:程序博客网 时间:2024/06/06 09:20

参考《Effective C++》P173;

  

class A{

public:

void f(){

cout << "f()" << endl;

}

  

void f(int i){

cout << "f(int)" << endl;

}

};

  

int main() {

void (A::*pf)() = &A::f;

A a;

(a.*pf)();

return 0;

}

class A{

public:

void f(){

cout << "f()" << endl;

}

  

void f(int i){

cout << "f(int)" << endl;

}

};

  

int main() {

void (A::*pf)(int i) = &A::f;

A a;

(a.*pf)(3);

        return 0;

}

  

#include<iostream>

  

using namespace std;

  

class Test{

public:

void f(){

cout << "hello, world" << endl;

}

static void sf(){

cout << "hello, world" << endl;

}

};

  

int main(){

void (Test::*pf)() = &Test::f;

(Test().*pf)();

  

void (*spf)() = &Test::sf; // Test::sf also works

spf();

return 0;

}

  

注意,取非静态方法的函数地址必须使用&,否则

  

  

0 0