我的类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, "Completely random", 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"
有没有一种方法可以让我提前声明最佳实践中的功能?还是我应该后悔我糟糕的设计选择,重新开始?
"非静态成员函数(实例方法(有一个隐式参数(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
};