关于我 class 中 const 方法的几个问题

A few questions about const methods in my class

我是在我的公司使用 C++ 编写企业软件的新手,成员函数中 const 的使用让我很困惑。例如,我有以下方法:

string DAC::impulse_find(int i)

不会修改变量i。当我使用将 const 添加到上述方法的这三种变体时,我的代码可以完美编译:

const string DAC::impulse_find(const int i) const

const string const DAC::impulse_find(const int i) const

string const DAC::impulse_find(const int i) const

那么这三者到底有什么区别呢?我查看了一些过去的答案并说 "It applies to whatever is to the left" 但这仍然令人困惑。它是否也适用于任何事物,例如 class 的名称?

没有区别

const std::string  
std::string const

const 的顺序无关紧要,因为您不是在处理指针。

有许多 const 作为限定词没有意义。您是否将编译器的警告级别调到最大?

编辑 1:指针和 Const
由于您要返回变量的副本,因此 const 的有效性毫无价值。无法修改函数中的原始项目,因为您返回的是副本。

也许您对 pointer 语法感到困惑,其中 const 的位置很重要:

string const * const -- constant pointer to a constant (read-only string).  Pointer cannot be modified.
string const *       -- Mutable pointer to a constant (read-only) string.  Pointer value can change.
string       * const -- Constant pointer to a read/write string.  Pointer value cannot be changed.
string       *       -- Mutable pointer to a read/write string.  Pointer value can be changed.  

只读数据的const可以放在类型之前或之后:

const string *  
string const *

以上两者是等价的

所有三个版本

const string …
const string const …
string const …

相同

const 的位置在这里无关紧要。第二个版本中重复的 const 是多余的,您的编译器应该对此发出警告。

此外,const 在这里没有意义,因为字符串是 returned 作为副本 。返回 const 值不会给您带来任何好处(参见 KABoissonneault 的评论),只有 引用或指向 const 的指针 才有意义,因为 return类型。