静态成员未被更新

static member is not being updated

本文关键字:更新 静态成员      更新时间:2023-10-16

我遇到过一些非常奇怪的行为。在我的类中,我有QFileSystemModel声明为静态变量,这个变量在actor中初始化,并且它有效,但是一旦我尝试更新其状态(通过这个类的一些方法),这似乎没有任何影响。但只要我把这个变量改成非静态的,一切都能正常工作。关于静态变量,我遗漏了什么?

class X:public QDialog
{
Q_OBJECT
static QFileSystemModel* model_;
public:
void update();
};
//cpp file
X::QFileSystemModel* model_  
X::X()
{
model_ = new QFileSystemModel(this);
}
void X::update()
{
model_->setNameFilters("*.h");//this will have absolutely no effect unless I make  
//model_ non static
}

您需要这样做,以防止多次初始化model_:

//cpp file
X::QFileSystemModel* model_ = 0; // Not strictly necessary, but good for clarity
X::X()
{
if (model_ == 0) model_ = new QFileSystemModel(this);
}

因为你正在为你的类X的每个新实例创建一个新的model_(每次构造函数运行),你所描述的问题似乎归结为一些很长的行;覆盖。

X::update中设置一些状态后,它可能会被另一个新创建的实例覆盖。

这是我所能给你的最好的答案了,我不需要更多关于这件事的信息。

简单样品溶液

struct Obj {
  Obj () {
    std::cerr << "model_: " << *model_ << std::endl;
    ++(*model_);
  }
  static int * model_;
};
int * Obj::model_ = new int (); // initialize the static member
int
main (int argc, char *argv[])
{
  Obj a, b, c;
}

输入错误?

我猜你的代码片段的这一部分包含一个打字错误,因为构造函数不能有返回类型。

X::QFileSystemModel* model_  
X::X()
{
model_ = new QFileSystemModel(this);
}