我仍在研究我的 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/