gpt4 book ai didi

c++ - 具有两个 getInstance() 方法的单例移交父指针?

转载 作者:行者123 更新时间:2023-11-30 05:39:47 24 4
gpt4 key购买 nike

我仍在研究我的 Logger我喜欢 Singleton 的想法,但我的 Logger 派生自 rm QDialog,因此我想在我第一次调用它时处理我的 Parent QWidget* MainWindow 指针:

class Logger : public QDialog {
Q_OBJECT

private:
explicit Logger(QWidget* parent = 0);

public:
static Logger& firstInstance(QWidget* parent = 0) {
static Logger theInstance(parent);
return theInstance;
}
static Logger& instance() {
return theInstance;
}
//..
}

所以我将从我的主窗口调用 Logger::firstInstance(this);。和来自其他地方的 Logger::instance() 。但是我的编译器模拟了:

Error: 'theInstance' was not declared in this scope: return theInstance;

在第二个 instance() 方法中。

最佳答案

你实际上应该从 instance 调用 firstInstance,因为你在 firstInstance 中有静态变量,它只会在第一次调用时初始化,然后刚刚返回已经初始化的变量。

  static Logger& instance() {
return firstInstance();
}

但实际上,公共(public)接口(interface)中的函数 firstInstance 不是一个好主意,可能将其设为私有(private)并声明 MainWindow 友元类会更好。

关于c++ - 具有两个 getInstance() 方法的单例移交父指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32120691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com