const 成员函数中的 const 参数

Nab*_*ren 0 c++ constants function-qualifier

我读过 const 的用例,我觉得我对 const 的大部分都有很好的理解。但是,我似乎无法弄清楚为什么我不经常看到这种情况:

void someFunction(const string& A) const
Run Code Online (Sandbox Code Playgroud)

const 成员函数中有 const 参数。出于某种原因,每当我查找示例并且该函数是 const 时,const 似乎都被从参数中删除,如下所示:

void someFunction(string& A) const
Run Code Online (Sandbox Code Playgroud)

然而,这似乎并没有阻止我修改 A。在 const 成员函数中使用 const 参数是否被认为是不好的形式?

如果 A 不被修改,那么参数中不保留 const 的原因是什么?

编辑:这是我没有澄清的错误,但我理解在参数之前添加它和在函数之后添加它之间的区别。我看过的很多代码都没有将两者结合起来,我只是想弄清楚这是否有原因。

Nem*_*ric 5

void someFunction(const string& A) const
Run Code Online (Sandbox Code Playgroud)

最后一个const意味着该方法不会改变其内部引用的对象的状态*this。第一个const是说该函数不会更改参数的状态 - 并且它与第二个没有任何相关性const,因此您可能会这样:

void someFunction(string& A) const
Run Code Online (Sandbox Code Playgroud)

在这种情况下,函数可能会更改A参数的状态,但可能不会更改其对象的状态。

例如(这是一个高度假设的例子):

class MyIntArray
{
 // some magic here in order to implement this array    

public:
 void copy_to_vector(std::vector<int> &v) const
 {
    // copy data from this object into the vector.
    // this will modify the vector, but not the
    // current object.
 }

}
Run Code Online (Sandbox Code Playgroud)

这是将两者结合起来的示例:

class MyOutput
{
    char prefix;
    // This class contains some char which
    // will be used as prefix to all vectors passed to it
public:
     MyOutput(char c):prefix(c){}
     void output_to_cout(const std::vector<int> &i) const
     {
        // iterate trough vector (using const_iterator) and output each element
        // prefixed with c - this will not change nor the vector
        // nor the object.
     }

}
Run Code Online (Sandbox Code Playgroud)

哦,看看这个问题:Use of 'const' for functionparameters