0

I need a user defined set according to the order I want. But When I wanted to access set members I got error The object has type qualifiers that are nor compatible with member function (I get this error when I place mouse pointer on error line. The error mentioned in title is fromm Error List after build)

typedef struct tagRECT
{
    long    left;
    long    top;
    long    right;
    long    bottom;
} RECT;

struct LabelRect : public RECT
{
    bool isIsolatedFrom(LabelRect* pRect)
    {
        if (pRect->right < left ||
        pRect->left > right ||
        pRect->top > bottom ||
        pRect->bottom < top)
            return true;
        return false;
    }
};
class CDrawnLabel
{   public:
    LabelRect     m_LabelRect;
    LabelRect* getLabelRect(){ return &m_LabelRect; }
    bool operator<(CDrawnLabel & rhs)
    {
        //This is the set ordering
        return getLabelRect()->right < rhs.getLabelRect()->right;
    }
}

I have a set like following

typedef std::set<CDrawnLabel> DrawnLabelSet;
DrawnLabelSet m_setDrawnLabel

I got error when I tried to access set members

    DrawnLabelSet::iterator itbegin,itend;
    LabelRect* pRectSecond;

    itbegin=m_setDrawnLabel.begin();
    itend=m_setDrawnLabel.end();
    pRectSecond=(*itbegin).getLabelRect();// Here I get the error.
Farsan Rashid
  • 1,460
  • 4
  • 17
  • 28

2 Answers2

4

The reason you get this error is because keys inside std::set<T> are stored as const T. So this expression (*itbegin) returns a const CDrawnLabel. Only const member functions can be called from a const object.

You will have to make getLableRect const. Also since const member functions can only return const pointers/references the member should be:

const LabelRect* getLabelRect() const { return &m_LabelRect; }

Not required but it would be a good idea to make your comparator const as well since it's not modifying any data. Another improvement that can be done is instead of taking a reference you should pass a const ref to the comparator.

bool operator<(const CDrawnLabel &rhs) const
{
    //This is the set ordering
    return getLabelRect()->right < rhs.getLabelRect()->right;
}
bashrc
  • 4,725
  • 1
  • 22
  • 49
1

The problem here is that std::set<>::iterator is actually a const_iterator so (*itbegin) has the type const CDrawnLabel&. Why is this? Well, if you could change the reference in the set, you could invalidate the ordering. So you need to take the object out of the set, modify it and then put it back in. Or, if you don't want to change it you could define a const function getConstLabelRect()

bgp2000
  • 1,070
  • 13
  • 32
  • std::set<>::iterator is returning a iterator. The type of the value pointed by the iterator is itself const. – bashrc Mar 31 '16 at 09:39
  • Isn't that exactly what a const_iterator is? If I look into my STL implementation, iterator and const_iterator are typedefs for the same thing. – bgp2000 Mar 31 '16 at 09:45