c++ - 如何创建对 const 指针的 const 引用?

标签 c++

我想创建以下类,但编译器给出错误(它告诉我们方法的签名是相同的):

struct entities_set_less
{   
    constexpr bool operator()(const ContentEntity*& _Left, const ContentEntity*& _Right) const
    {   // apply operator< to operands
        return (_Left < _Right);
    }

    constexpr bool operator()( const const ContentEntity*& _Left, const const ContentEntity*&_Right) const
    {   // apply operator< to operands
        return (_Left < _Right);
    }
};

从我的角度来看,像 const const ContentEntity*& 这样的表达式意味着“对 const ContentEntity 上的指针的 const 引用”。它应该与 const ContentEntity*& 不同,后者只是“对非 const 类型上的指针的 const 引用”。

最佳答案

首先,让我们澄清(或尝试)您真正想要的是什么。你说你想要一个“const引用”……但无论如何,引用(实际上)是const(即,一旦引用变量绑定(bind)到其目标,它随后就不能绑定(bind)到不同的目标)。

因此,您的意思可能是希望第二个重载中的参数是对指向常量对象的常量指针的引用;也就是说,指针和对象都不能修改(在第一次重载中,指向的对象不能修改,但引用的指针可以。

要使指针const,您需要在指针指示符(*)之后添加该关键字。像这样:

struct entities_set_less {
    constexpr bool operator()(const ContentEntity*& _left, const ContentEntity*& _light) const
    {   // references to non-const pointers to const objects
        return (_left < _light);
    }
    constexpr bool operator()(const ContentEntity* const& _left, const ContentEntity* const& _right) const
    {   // references to CONST pointers to const objects
        return (_left < _right);
    }
};

请注意,我还将您的 _Left_Right 标识符更改为 _left_right,因为 ID 开头下划线后跟大写字母的被保留。来自 this C++17 Draft Standard :

5.10 Identifiers       [lex.name]


(3.1)     — Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.

关于c++ - 如何创建对 const 指针的 const 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72261075/

相关文章:

c++ - 带状态栏的对话框

c++ - 友元函数和复制构造函数

c++ - 我怎样才能模一个大的整数值

c++ - C++ 中的复合类型、const 和 auto

c++ - std::wistringstream 解析时可以忽略字符串中的空格吗?

c++ - Mingw-w64 + 代码块 : No such file or directory

c++ - 一个人的嵌入式项目示例

c++ - (c++) 返回和函数输出之间的错误

c++ - 模板类的专用构造函数

c++ - 指向成员转换的指​​针