开发者

Singleton class issue in Qt

i created a singleton class and trying to access that class in other class but getting error "cannot access private member"

Setupconfig is my singleton class and i am trying to access this class in other class which have QMainWindow

And here is the error message:

Error 'Setupconfig::Setupconfig' : cannot access private member declared in class 'Setupconfig'

Setupconfig.h
static Setupconfig *buiderObj()
{
    static Setupconfig *_setupObj= new Setupconfig();
    return _setupObj;
}

private:
Setupconfig();

//////////////////////////////////////
EasyBudget.h
class EasyBudget : public QMainWindow, public Ui::EasyBudgetClass, publ开发者_开发百科ic Setupconfig
{
Q_OBJECT
public:
Setupconfig *setupObj;
}

//////////////////////////////////////
EasyBudget.cpp
EasyBudget::EasyBudget(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent,Qt::FramelessWindowHint)
 {
 setupObj=Setupconfig::buiderObj();
 }


You should declare the static member in a source file not in a header file, whether or not you use the static class member or static function member approach. Your basic appoach should work, if the instance() function is a public member:

//setupconfig.h
class Setupconfig 
{
 public:  

static Setupconfig* instance();


private:
        SetupConfig();
};

//setupconfig.cpp
static Setupconfig* SetupConfig::instance()
{
   static Setupconfig* _setupObj= new Setupconfig();
   return _setupObj;
}

SetupConfig::SetupConfig()
{
    //....
}

Using the class member approach is also possible

//setupconfig.h
class Setupconfig 
{
 public:  

static Setupconfig* instance();


private:
        SetupConfig();

        static Setupconfig*  _setupObj;
};

//setupconfig.cpp
Setupconfig*  Setupconfig::_setupObj = 0;

static Setupconfig* SetupConfig::instance()
{
   if (_setupObj == 0) {
        _setupObj = new Setupconfig;
   }
   return _setupObj;
}

SetupConfig::SetupConfig()
{
    //....
}


Why are you deriving "EasyBudget" from the singleton class "SetupConfig"?

Remove that part to resolve your problem.

EasyBudget.h
class EasyBudget : public QMainWindow, public Ui::EasyBudgetClass
{......


Try This

 public:
    static Setupconfig *buiderObj() 
    { 
        if(*_setupObj; != null)
        {
           _setupObj= new Setupconfig(); 
        }
    return _setupObj; 

    } 
    public:
    Setupconfig(){}
    private:
    Setupconfig *_setupObj;


There are drawbacks in this approach, both copy constructor and assignment constructors (as generated by C++ compiler by default) will make a copy of the so called singleton class (here names: SetupConfig). You should also declare those tow constructors as private well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜