如果 std::basic_string::operator[] 也是一个非常量方法,为什么它是一个 const 方法?

Why is std::basic_string::operator[] a const method if it's also a non-const method?

http://cplusplus.com/reference/string/basic_string/operator[]

我知道有第二个版本 returns const 可以防止在需要 const 结果时发出警告并减轻转换但如果函数已经提供了非 const 方法(方法--不是结果)那么声明 const-结果方法 const 的意义何在?

如果函数没有 const 版本,则无法在 const 实例上调用该函数。例如:

void func (const std::string &h)
{
    if (h[0] == "hello")
        ...
}

如果没有 operator[]const 版本,这将如何工作?

假设你有

const std::string str{"test"};
std::cout << str[2];

如果您没有 const 成员函数,上面的代码将失败,因为隐式传递给 operator[]this 指针是 const

如果你有一个 const std::basic_string 你不能调用 (non-const) std::basic_string::operator[],因为它没有标记为常量。

const 方法 returns 不同的类型,它 returns 一个 const 限定引用。这意味着如果使用 const 方法,则该方法的结果是 const 限定的(因此是“不可变的”)。非 const 限定方法 returns 一个常规引用​​,它是“可变的”。

你不能 const方法,否则你不能修改非const限定的单个字符std::basic_string 对象。而且你不能 只是 const 方法,否则你将无法在 const-qualifed std::basic_string 上调用该方法对象。

您需要了解,第二个 (const) 版本不仅 returns 一个不同的结果,而且还将自己标记为 const(这是声明末尾的第二个const):

const_reference operator[] (size_type pos) const;

这是两个不同的东西:const return 值本身在非 const 方法的存在下是不需要的(因为 non-const return 值始终可以转换为 const 版本)。

但是没有 const 版本的运算符意味着您不能在 const 字符串对象上使用它。

const 结果只是运算符本身的 constness 的结果:如果你有一个 const 字符串并使用运算符获取对单个字符串的引用字符,显然此引用也必须是 const(如果不是,您可以更改 const 字符串中的单个字符)。