我最近开始使用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
将其设为常量,因为我也需要使其变为常量。
错误:“非静态成员引用必须相对于特定对象”
我想我无法创建的新实例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?
}
};
根据定义,类的静态成员函数独立于该类的任何非静态成员的状态。这意味着您可以在没有对象的情况下使用它。
一旦依赖非静态成员,您的函数就必须是非静态的:
class MyClass
{
bool eventActive = false;
public:
bool JoinCommand() // non static, because
{
if (eventActive == true) // it depends clearly on the state of the object
{ /* do something here... */ }
}
};
然后,您可以按预期方式调用成员函数:
MyClass omc;
if (omc.JoinCommand())
cout << "Command joined successfully"<<endl;
但是,如果您有正当的理由保持函数静态:
在静态成员函数中访问非静态元素的唯一方法是告诉函数必须使用哪个对象来获取非静态元素(参数,全局对象等)。就像您将课程上课一样。
例子:
class MyClass
{
bool eventActive = false;
public:
static bool JoinCommand(MyClass& omc) // example by provding a parameter
{
if (omc.eventActive == true) // access non static of that object
{ /* do something here... */ }
}
};
您可以这样称呼它:
MyClass obj;
if (MyClass::JoinCommand(obj)) // a little bit clumsy, isn't it ?
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句