C ++函数指针在类写法对比

情况一、函数指针不使用类的写法
–文件main.cpp

#include <iostream>
#include <string>

typedef void(*function)();
function assignPtr;
std::string name;
    
void Test();
void morning();
void say(std::string a);

void Test() {assignPtr = morning;}
void morning() {std::cout <<"Good morning," << name << std::endl;}
void say(std::string a) {name = a; assignPtr();};


int main() {
    Test();
    say("Miguel");
}

运行结果:

情况二、函数指针使用类的写法

#include <iostream>
#include <string>

class Test {
  public:
    
    Test() {assignPtr = &Test::morning;}
    void say(std::string a) {name = a; (this->*assignPtr)();};
  private:
    typedef void(Test::*function)();
    void morning() {std::cout <<"Good morning," << name << std::endl;}

    function assignPtr;
    std::string name;
};

int main() {
    Test a;
    a.say("Miguel");
}

运行结果:

主要区别在于

在类中需要正确的使用类型

typedef void(Test::*function)();
然后在创建指针和调用指针时都调整语法。
Test() {assignPtr = &Test::morning;} // Get pointer-to-member
void say(std::string a) {name = a; (this->*assignPtr)();};  // Use pointer-to-member

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注