[Qt-interest] how to pass the reference to QMap to other class

BERAUD Alexandre aberaud at infflux.com
Fri Sep 9 14:21:58 CEST 2011


QMap<int,DataStruct>& myMap;
This is an uninitialized reference, which is invalid and is just 
tolerated by your compiler.

myMap(firstClass->getMap())
Here you use the copy constructor of the class and I guess some hidden 
dereference is involved.
In my opinion it is better to access the QMap through the firstClass 
pointer because the use of references often leads to unreadable code 
with the compiler performing some magic behind the scene.

Regards,

Alex


Le 09/09/2011 12:38, franki a écrit :
>
> Hi all,
>
> I have one class where i have QMap which has some data, I want to be 
> able to easly access this data in second class, so what I want is to 
> pass this QMap from first class to second class as a reference 
> (without copying data).
>
> I googled and I've done it like this (snippet of code):
>
> first class header :
>
> public:
>
> FirstClass(QObject *parent)
>
> QMap<int,DataStruct> myMap;
>
> public slot:
>
> QMap<int,DataStruct>& getMap();
>
> first class body:
>
> QMap<int,DataStruct>& FirstClass::getMap() {
>
> return myMap;
>
> }
>
> second class header:
>
> public:
>
> SecondClass(Ui::MainPages m,FirstClass *firstClass);
>
> private:
>
> Ui::MainPages mp;
>
> FirstClass *firstClass;
>
> QMap<int,DataStruct>& myMap;
>
> second class body:
>
> SecondClass::SecondClass(Ui::MainPages m,FirstClas *firstClass): 
> QWidget(),myMap(firstClass->getMap())
>
> {
>
> mp=m;
>
> this->firstClass=firstClass;
>
> }
>
> So the problem is wierd, when I change data of the item in QMap in 
> firstClass I can see the change in secondClass by accessing private 
> variable myMap,
>
> but when I add new member to QMap in firstClass I can't see this new 
> member in secondClass by using private variable myMap, although I can 
> access this new member when I'm using pointer to first class like this:
>
> firstClass->myMap
>
> What is wrong with this, and how should I do that properly?
>
> I'm aware that in second class I can access QMap by pointer to first 
> class:
>
> firstClass->myMap
>
> but I wanted to have reference to myMap in second class without using 
> pointer to first class.
>
> please advise me.
>
> best regards
>
> Marek
>
>
>
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at qt.nokia.com
> http://lists.qt.nokia.com/mailman/listinfo/qt-interest

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20110909/02a89fab/attachment.html 


More information about the Qt-interest-old mailing list