我正在运行一些示例程序来重新熟悉 C++,我遇到了以下问题。首先,这是示例代码:
void print_string(const char * the_string)
{
cout << the_string << endl;
}
int main () {
print_string("What's up?");
}
在上面的代码中, print_string
的参数可能是 const char * const the_string
。哪个更正确?
我知道区别在于一个是 pointer to a constant character
,而另一个是 constant pointer to a constant character
。但为什么这两种方法都有效?什么时候相关?
原文由 pict 发布,翻译遵循 CC BY-SA 4.0 许可协议
后者阻止您修改
the_string
内部print_string
。它实际上在这里是合适的,但也许冗长推迟了开发人员。char* the_string
:我可以更改哪个char
the_string
指向,我可以修改char
指向的 —1ab9b4da34b4c1253c 8.3ecfbcaconst char* the_string
: I can change whichchar
the_string
points to, but I cannot modify thechar
to which it points.char* const the_string
: I cannot change whichchar
the_string
points to, but I can modify thechar
to which it points.const char* const the_string
:我无法更改哪个char
the_string
指向,我也不能修改char
指向的 —015180010a530749b.