0

I have a class orders which has its instanced stored in a QMap/Map and has a Key:int, value:order pattern. Everything went fine until I started iterating through the map and accessing the functions of the class.First I was trying to print out the order objects values using it's getter methods for example:

orderSet.value(i).getDate().toString("dd/MM/yyyy");
//OrderSet is my map

This however produced an error

error: passing 'const order' as 'this' argument of 'QDate order::getDate()' discards qualifiers [-fpermissive]

I then fixed this by adding 'const' to the getter methods and the previous line of code would successfully run and print out that objects date as a string.

However now the issue is I cant implement my setter methods because I would get the same error, and obviously the setter method has a line which alters the original member variable so this in itself would violate the constant rule, so how can I alter the object variables within a map ??

heres my code if it helps:

class order
{
    QDate dateOrdered;
    int totOrders;
    double totValue;

public:
   order();
   order(QDate,int,double);
   //Sets
   void setDate(QDate); //Cant add const since values are being altered
   void setOrderTot(int);
   void setValueTot(double);

   //Gets
   QDate getDate() const; //Adding const solved these methods 
   int getOrderTot()const;
   double getValueTot()const;

};

#endif // ORDER_H
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
MrSSS16
  • 449
  • 3
  • 7
  • 21
  • It seems like you have an `const` object of `order` so you can call only const member functions on it.If you need to modify the members of the object, the object should not be `const`. – Alok Save Sep 26 '12 at 07:54
  • so if im correct you mean when I create the object ??so `order myObject;` is declared as a constant ?? Not too sure what you mean – MrSSS16 Sep 26 '12 at 08:26
  • No, `order myObject` is non-const. What Als means is that you might have declared `const order myObject`, or used a construct with similar effect. – DevSolar Sep 26 '12 at 08:42
  • nope I checked and what you see with the code above is all there is in the class...when I create the object the first time its created using `order myOrder(Qdate theDate,int total,double totalvalue);` – MrSSS16 Sep 26 '12 at 08:53

1 Answers1

1

QMap::value() returns a const T, so you can not call non const member functions on it. Moreover, it returns a copy of the object in the map, so calling a setter would not do what you think, and the object in the map would be unchanged. The only member function that returns a reference is operator[], but keep in mind that you first need to check if the map contains the key with contains(), because operator[]will add it to the map.

Or, you could use an iterator to access an item and modify it.

QMap<int, order>::iterator it = orderSet.find(i);
if (it != orderSet.end()) {
    // Found it
    it->callSetter();
}
Claudio
  • 1,658
  • 11
  • 18