具有指向函数的指针的类内的结构是否需要类外函数的前向声明
struct inside a class that has a pointer to a function requires forward declaration of functions outside of the class?
我的类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
};
相关文章:
- Visual Studio中的函数声明和函数定义问题
- 为什么函数声明中允许 const?
- 如果 x.h 仅由函数声明组成,为什么有必要在 x 中包含 x.h.cpp
- * 和 ** 在 C++ 函数声明中是什么意思?
- 构造函数/函数声明参数列表中的统一初始化
- 在将函数声明为友元时,尖括号的含义是什么?
- 为什么转换函数声明不需要至少一个定义类型说明符
- 如何正确编写指针函数声明?
- 在"template"和函数声明之间使用:template<typename trait> using tr = base_trait<trait> void fn(tr::t
- 为什么要将函数声明和定义放在单独的文件中
- 为什么系统日志有两个不同的函数声明?
- 我如何获取数组的大小,以便我可以从函数声明所述数组
- 使用 enable_if 在按值传递与按引用传递之间更改函数声明
- JavaScript 中的一等函数和 C++ 中的函数声明
- C++ 通过函数声明后初始化向量
- VS2017 #error: : snprintf 的宏定义与标准库函数声明冲突
- C++ 17 个友元函数声明和内联命名空间
- MSVC 2017 - 错误 - 如何将模板类 X 的模板成员函数声明为嵌套类 X::Y 的好友
- 将派生类的构造函数声明为父类的友元
- 用于从 ANSI 字符串转换为 std::basic_string <TCHAR>的正确函数声明