【发布时间】:2016-02-12 19:40:06
【问题描述】:
我最近开始使用 C++,偶然发现了一个我似乎无法理解的问题。
class MyClass
{
bool eventActive = false;
static bool JoinCommand()
{
if (eventActive == true) // eventActive error: "a nonstatic member reference must be relative to a specific object"
{
// do something here...
}
else
{
}
};
我需要JoinCommand 是静态的,但我还需要使用eventActive,它必须是非静态的,并且由同一类中的其他函数使用/修改。因此我不能将 eventActive 设为静态,因为我还需要将其设为 const。
还有错误: “非静态成员引用必须相对于特定对象”
我想我无法创建MyClass 的新实例。那么我该怎么处理呢?或者有什么我不理解/我误解的错误?任何帮助将不胜感激。
编辑:
感谢大家帮助我解决这个问题。我完成了自己想要实现的目标,但在学习新事物时,我偶然发现了另一个与此类似的问题。
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?
}
};
【问题讨论】:
-
“我需要 JoinCommand 是静态的”,为什么。
-
请阅读一本合理的关于静态的 C++ 教科书
标签: c++ function static instance non-static