用常量字符串和字符串常量声明字符串有什么区别

What is the difference between declaring a string with const string and string const

本文关键字:字符串 常量 什么 区别 声明      更新时间:2023-10-16

>我正在浏览网上的一些代码,我看到了这两个声明,

const std::string strFoo = "MyFoo";

std::string const strBar = "MyBar";

我对 const 关键字的不同位置感到困惑。它的目的究竟是什么?

谢谢!

在这种情况下,

没有区别

对于更复杂的声明,可能会有很大的不同。

你可以说const适用于左边的东西,如果那里什么都没有,它适用于右边的东西。

例如const指向 int 的指针上使用限定符:

const int* ptr1;        // (1.) pointer to const int
int const * ptr2;       // (2.) same as 1.
int* const ptr3;        // (3.) const pointer to int
const int* const ptr4;  // (4.) const pointer to const int
int const * const ptr4; // (5.) same as 4.

有关如何读取复杂类型声明的更多信息,请参阅以下内容: C 左右规则