C++ 函数指针赋值不能转换类内的类型

标签 c++ function class pointers

<分区>

我有一个简单的类,它有一个指向函数的指针。构造函数将其指向函数“morning()”,我在编译时收到错误消息:

error: cannot convert ‘Test::morning’ from type ‘void (Test::)()’ to type ‘Test::function {aka void (*)()}’
     Test() {assignPtr = morning;}

当在函数外部声明“morning()”和 typedef 时,代码确实可以编译,我不知道如何让它在当前类中工作。

#include <iostream>
#include <string>

class Test {
  public:
    Test() {assignPtr = morning;}
    void say(std::string a) {name = a; assignPtr();};
  private:
    typedef void(*function)();
    void morning() {std::cout << "Good morning, " << name << std::endl;}
    void night() {};
    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

关于C++ 函数指针赋值不能转换类内的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43944112/

相关文章:

c++ - 移位寄存器74HC595输出电流

function - 如何定义动态嵌套循环python函数

php - 如何在 PHP 中给函数起别名?

php - 将多个参数传递给函数 php

java - 将变量从一个 Java 类获取到 GUI 形式 Java 类 JLabel

php - 声明函数时 'static'是什么意思

c++ - 对于下面给出的任务,使用类还是多维数组更好?

c++ - execv,选择并阅读

c++ - 在 C++ 中读取 CSV 文件中的两列

iPhone iOS 如何将 Class 对象与另一个类对象进行比较?