静态成员未被更新
static member is not being updated
我遇到过一些非常奇怪的行为。在我的类中,我有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);
}
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- (C++)为什么静态成员可以在初始化之前使用
- 类的全局对象和静态成员
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 模板化类中静态成员的延迟初始化
- 使用静态成员声明类时遇到问题
- C++:是否可以使用非静态成员变量模板?
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 如何在复杂继承中访问静态成员变量
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 静态成员变量不会由 gettext 转换
- decltype:使用指针访问类的静态成员
- 更新函数调用中的静态成员会导致崩溃
- 静态成员未被更新
- 在C++中更新静态函数中的非静态成员