具有指向函数指针的类中的struct是否需要在类外部进行函数的前向声明?

我的类Menu中有一个私有结构,其中包含菜单项属性。这些属性之一是指向函数的指针。当我在类外转发声明函数时,似乎我写的东西行得通,但是在类外定义函数似乎是非常糟糕的做法。

#pragma once
#include <string>

//forward declaration outside the class
void completelyRandom();//does not throw error
class Menu
{

private:
    typedef void(*Menu_Processing_Function_Ptr)();

    struct MenuItem
    {
        unsigned int  number;
        const char *  text;
        Menu_Processing_Function_Ptr p_processing_function;
    };

    MenuItem menu[] =
    {
        {1,"Completely random",completelyRandom}

    };

public:
    Menu();

    ~Menu();
};

这是一些引发错误但更接近我希望的代码:

#pragma once
#include <string>


class Menu
{

private:
    typedef void(*Menu_Processing_Function_Ptr)();

    struct MenuItem
    {
        unsigned int  number;
        const char *  text;
        Menu_Processing_Function_Ptr p_processing_function;
    };

    MenuItem menu[1] =
    {
        {1,completelyRandom}

    };

public:
    Menu();
    //declaration within the class
void completelyRandom();//does throw error
    ~Menu();
};

我尝试在Menu范围内到处移动completelyRadom()声明,但出现错误

a value of type "void (Menu::*)()" cannot be used to initialize an entity of type "Menu::Menu_Processing_Function_Ptr"

有没有一种方法可以向前声明最佳实践中的功能?还是我应该为我糟糕的设计选择感到遗憾并重新开始?

jiedong0827 回答:具有指向函数指针的类中的struct是否需要在类外部进行函数的前向声明?

“非静态成员函数(实例方法)具有一个隐式参数(this指针),该参数是指向它所操作的对象的指针,因此必须将对象的类型包括为该对象的类型的一部分。函数指针。“-https://en.wikipedia.org/wiki/Function_pointer

查看此代码以获取示例:

#pragma once
#include <string>

class Menu
{

private:
    //By specifying the class type for the pointer -> 'Menu::' in this case 
    // we no longer have to forward declare the functions
    //outside of the class
    typedef void(Menu::*Menu_Processing_Function_Ptr)();

    struct MenuItem
    {
        unsigned int  number;
        const char *  text;
        Menu_Processing_Function_Ptr p_processing_function;
    };

    MenuItem menu[1] =
    {
        {1,"Completely random",completelyRandom}

    };

public:
    Menu();
void completelyRandom(); // no longer throws an error
};
本文链接:https://www.f2er.com/3154714.html

大家都在问