c++ - 无法将 'this' 指针从 'const CDrawnLabel' 转换为 'CDrawnLabel &'

标签 c++ set

我需要一个根据我想要的顺序的用户定义集。但是当我想访问集合成员时出现错误 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/

相关文章:

c++ - 多线程多队列..如何管理它?

c++ - 如何使用 C++ 在 Windows 上检索分页文件大小的 "Minimum allowed"/"Recommended"/"Currently allocated"值?

c++ - 如何创建一个 std::set 结构?

python 集 : why is my_set = {*my_list} invalid?

java - 按照惯例,Java 中的 set() 方法可以返回值吗?

c++ - IntelliSense 错误标识符 "emlrtStack"未定义

c++ - 使用 `std::cin` 从用户那里准确读取 4 个字符到字符数组中

c++ - 手电筒 (arrayfire) 中的 torch.squeeze 和 torch.unsqueeze 等价物

python - 从组合表中创建成功的组合

java - 迭代器和Listiterator的区别?