从静态函数调用非静态变量
Calling a non-static variable from a static function
我在学习C++的过程中尝试做某事时遇到了一个问题,但我不确定如何处理这种情况:
class Command
{
public:
const char * Name;
uint32 Permission;
bool (*Handler)(EmpH*, const char* args); // I do not want to change this by adding more arguments
};
class MyClass : public CommandScript
{
public:
MyClass() : CommandScript("listscript") { }
bool isActive = false;
Command* GetCommands() const
{
static Command commandtable[] =
{
{ "showlist", 3, &DoShowlistCommand } // Maybe handle that differently to fix the problem I've mentioned below?
};
return commandtable;
}
static bool DoShowlistCommand(EmpH * handler, const char * args)
{
// I need to use isActive here for IF statements but I cannot because
// DoShowlistCommand is static and isActive is not static.
// I cannot pass it as a parameter either because I do not want to
// change the structure of class Command at all
// Is there a way to do it?
}
};
任何帮助将不胜感激! :)
// Is there a way to do it?
不。
要么将其作为参数传递,要么将其设为静态,要么DoShowlistCommand
设为非静态。
这里有两个可能的答案:
1. 关于在静态函数中使用非静态项:
正如我们在上一个问题/答案中所说,这是不可能的,除非您在静态函数中具有特定的MyClass
对象(并使用object.isActive
(。 不幸的是,你不能在这里这样做:
- 您的代码注释清楚地表明您无法向函数调用添加
MyClass
参数; - 现有参数并不表示您已经有指向父类对象的指针; 在这种情况下
- 使用全局对象是不可接受的。
2. 关于您要做的事情:
您似乎希望函数是静态的,因为您希望在将脚本命令映射到函数指针的表中提供它。
备选方案A
如果 commandtable
中使用的所有函数指针都是 MyClass
的成员,则可以考虑使用指向成员函数的指针而不是指向函数的指针。 在对象上设置 isActive 的外部对象/函数可以将指针引用到它知道的 MyClass 对象上的成员函数。
备选案文B
使用命令设计模式修改代码设计以实现脚本引擎:它非常适合此类问题。 这将需要对代码进行一些重构,但之后它将更加易于维护和可扩展!
我认为
没有任何办法可以做到这一点。原因如下:静态成员函数不附加到任何特定对象,这意味着它无法访问其他非静态成员,因为它们附加到对象。
看起来不需要将其设置为静态成员。如果您确定这样做 - 则将其作为参数传递。例如,制作一个
函数bool isActive((;
,并在您调用此"有问题"函数时将参数从它传递到该函数的某个地方。
您也可以将成员变量更改为静态,但看起来每个对象都需要它,而不是一劳永逸
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 模板基类中的静态变量
- 类和静态变量
- 不同作用域中的静态变量和全局变量
- 静态变量声明和定义
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 在类中继承静态变量?
- "local scope"中的 C++ 初始化静态变量
- 使用静态变量的递归调用的不同输出
- 复制文件流C++静态变量
- 跨模板化函数编译的静态变量
- C++编译器是否优化了顺序静态变量读取?
- C++,每个循环初始化一个新的静态变量
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 这些语句是否等效(静态变量、常量变量和泛型)
- 程序如何知道静态变量是否需要初始化?
- 类外的静态变量实例化
- 无法解析静态变量
- 函数局部静态变量:从性能角度来看的优点/缺点
- 访问从 CPP 文件到其他头文件的静态变量