函数指针的使用

在类中的使用案例:

#include <iostream>

class Method;  // forward declaration

class MethodPtr {
 public:
  void (Method::*func)() = nullptr;
};

class Method {
 public:
  Method();
  void doSomething();
  void call();  // will use methodptr
  MethodPtr methodptr;
};

Method::Method() : 
    methodptr{&Method::doSomething}
{}

void Method::call() {
  // dereferencing the function pointer to call it on `this`:
  // auto& p = methodptr.func; // p 指针指向 doSomething 函数地址
  // (this->*p)();
  (this->*methodptr.func)();
}

void Method::doSomething() {
    std::cout << "Did something!" << std::endl;
}

int main() {
  Method method;
  method.call();
}

结果:

Did something!
posted @ 2022-12-19 16:41  strive-sun  阅读(21)  评论(0编辑  收藏  举报