using a class's variable in another class func

2019-06-05 10:53发布

问题:

i have classes like this

class A : public QDialog
{
A(QWidget *parent);
static map<int,QString> dataa;
};

class B : public QThread
{
public void run();
}

class C : public QDialog
{
public void abc();
}

Defination of classes

void B::run()
{
in this function,i am using __dataa__ as __dataa.insert__which is defined initially in A class as public.
}

void C::abc()
{
in this function also,i am using __dataa__ as __dataa.find__ and dataa.end__ which is defined initially in A class as public.
}

Now please help me how can i use that variable dataa in the other two classes B and C.somewhere i seen we have to declare it as static and use it in the B and C class as A::data but its not working and giving error.

these three classes are initialized as

int main()
{
A window;
B datathread;
datathread.start
//B is Qthread inherited and A,C are QDialog inherited
}

class C is initialized from class A by clicking a pushbutton on it and opening its dialog in a new window. i guess this time i wont be blamed for not clearly formulating my question.please on gods name help me as i am stuck over this from long time.a big thanks in advance for any kind of help.

回答1:

undefined reference to A::dataa

You need to define it in A's .cpp file. Say:

std::map<int, QString> A::dataa;

Also to make sure this is accessible elsewhere there are two options:

  • declare this map object in the public section of A class
  • or have a copy of this object returned via a function like @Jeeva suggests.

Now, to access this variable in other units, you would first include the header file for A class.

#include "A.h" //or something similar..

And to access it:

void B::run() //and similar with C::run(..)
{
    A::dataa //do something with it ..
}


回答2:

I am not familiar with QT but i guess this might help. If you want to use class'A data in class b or c there are three options

  1. Inherit class B and C from class A if the relationship is meaningfull
  2. Create instance of class A inside class B & C (Containment)
  3. Access the class A's data through a public member function of class A like

    public:

       map<int, QString> GetData()
       {
         return dataa;
       }
    


标签: c++ qt class