问题
I am still working on my Logger and I like the idea of a Singleton but my Logger derives frm QDialog, thus I would like to handle my Parent QWidget* MainWindow pointer when I call it first:
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;
}
//..
}
So I would call Logger::firstInstance(this);
from my MainWindow. And Logger::instance() from elsewhere. But my compiler mocks:
Error: 'theInstance' was not declared in this scope: return theInstance;
in the second instance()
method.
回答1:
You should actually call just firstInstance
from instance
, since you have static variable in firstInstance
it will be initialized only on first call, then just returned already initialized variable.
static Logger& instance() {
return firstInstance();
}
But actually, function firstInstance
in public interface is bad idea, probably it will be better to make it private and declare MainWindow
friend class.
来源:https://stackoverflow.com/questions/32120691/singleton-with-two-getinstance-methods-handing-over-a-parent-pointer