我需要一个根据我想要的顺序的用户定义集。但是当我想访问集合成员时出现错误 The object has type qualifiers that are nor compatible with member function(当我将鼠标指针放在错误行上时出现此错误.标题中提到的错误是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;
}
}
我有一组如下
typedef std::set<CDrawnLabel> DrawnLabelSet;
DrawnLabelSet m_setDrawnLabel
当我尝试访问集合成员时出现错误
DrawnLabelSet::iterator itbegin,itend;
LabelRect* pRectSecond;
itbegin=m_setDrawnLabel.begin();
itend=m_setDrawnLabel.end();
pRectSecond=(*itbegin).getLabelRect();// Here I get the error.
最佳答案
出现此错误的原因是因为 std::set<T>
中的键存储为 const T
.
所以这个表达式 (*itbegin)
返回 const CDrawnLabel
.只能从 const 对象调用 const 成员函数。
您必须将 getLableRect 设为常量。此外,由于 const 成员函数只能返回 const 指针/引用,该成员应该是:
const LabelRect* getLabelRect() const { return &m_LabelRect; }
不是必需的,但将比较器也设为 const 是个好主意,因为它不会修改任何数据。可以做的另一项改进是,您应该将 const ref 传递给比较器,而不是采用引用。
bool operator<(const CDrawnLabel &rhs) const
{
//This is the set ordering
return getLabelRect()->right < rhs.getLabelRect()->right;
}
关于c++ - 无法将 'this' 指针从 'const CDrawnLabel' 转换为 'CDrawnLabel &',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36329125/