开发者

Access class function from different cpp (how to declare)

I have a problem with my Qt(c++) class.

Code:

SharedVariables.h

class SharedVariables
{
    private:
        QString TextoPesquisa;
        bool LoginEfectuado;

    public:
        SharedVariables();
        QString getTextoPesquisa();
        void setTextoPesquisa(QString TxtPesquisa);
        bool getLoginUtilizador();
        void setLoginUtilizador(bool UtilizadorComLogin);
};

SharedVariables.cpp

QString ShareVariables::getTextoPesquisa()
{
    return TextoPesquisa;
}

void ShareVariables::setTextoPes开发者_如何转开发quisa(QString TxtPesquisa)
{
    TextoPesquisa = TxtPesquisa;
}

bool ShareVariables::getLoginUtilizador()
{
    return LoginEfectuado;
}

void ShareVariables::setLoginUtilizador(bool UtilizadorComLogin)
{
    LoginEfectuado = UtilizadorComLogin;
}

Then to have access to the functions in my 2 (or more) cpp's, I use this :

File1.cpp (the one who writes)

SharedVariables e1;
e1.setTextoPesquisa("StringHERE");

File1.cpp (the one who reads)

SharedVariables e2;
qDebug() << e2.getTextoPesquisa();

The problem is that when the e2 is initialized my QString TextoPesquisa becomes empty again, And i don't know who to solve this problem, since I want that the values stay the same so I can access everywhere with this functions.


The variable need to be static:

class SharedVariables
{
    private:
        static QString TextoPesquisa;

Also make sure you declare TexttoPesquisa in cpp file:

QString SharedVariables::TextoPesquisa;

Because static variables aren't bound to particular class instance, they need their own memory location.


e2 is empty because you are using two different instances of the same class.

You need to create a SharedVariables object (on your main for example) and then use it on your various classes in .cpp files.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜