1

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

const std::string strFoo = "MyFoo";

std::string const strBar = "MyBar";

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

谢谢!

4

1 回答 1

4

在这种情况下,它没有任何区别

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

你可以说这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 Right-Left Rule

于 2013-10-27T03:51:19.777 回答