为什么 const MyClass const* 无效

Why is const MyClass const* not valid?

本文关键字:const 无效 MyClass 为什么      更新时间:2023-10-16

我对C++相当陌生,在尝试阅读这种原型时我会感到困惑。

此原型在Visual Studio 2012"构建"(本机C++静态库中,而不是C++/CLI),尽管它不会使指针恒定。我注意到它抛出了一个警告,我一开始没有看到。

C++ Visual Studio 2012

     int intTest =3;
     int intTest2 = 5;
     const int const* pointerTest = &intTest;
     pointerTest = &intTest2; //This works
     const int* const pointerTest2 = &intTest;
     pointerTest2 = &intTest2; //This doesn't build because the pointer is constant.

我意识到了我的错误,因为当我尝试在 Linux(使用 GCC 4.6.3 的 Eclipse)中构建此代码时,它抛出了一个错误:

重复的"常量"

我错误地写了这个而不是const MyClass* const,但我没有注意到它,因为Visual Studio没有抛出错误。

为什么这个语法是错误的?我不是故意写的,但我想理解。

>const将术语装饰在其左侧,除非它是最左侧,否则它会在其右侧装饰术语。

使用上述规则重写您的声明是

int const const* pointerTest = &intTest;

你应该写:

const int * const pointerTest = &intTest;

或者坚持正确的常量风格,不会感到困惑:

int const * const * const * const someEvilVariable = foo();

在此语句中

 const int const* pointerTest = &intTest;

限定符 Const 只是重复了。它相当于

 const int * pointerTest = &intTest;

 int const* pointerTest = &intTest;

这里定义了一个指针和一个常量数据。指针本身不是常量。

在此声明中

const int* const pointerTest2 = &intTest;

您将指针本身定义为常量。它只能在定义时初始化,并且不能更改。

const MyClass *MyClass const *都声明了一个指向常量数据的指针,因此MyClass的两边const都在做完全相同的事情,因此发出警告。

理解声明内容的一种技术是从右到左阅读声明,例如

MyClass const * const pointerTest = &intTest; //a const pointer to const data of type MyClass

但是,您可以将限定符放在类名旁边的任一侧,如下所示:

const MyClass * const pointerTest = &intTest; //a const pointer to data that is const.

其他可能的声明:

const MyClass * pointerTest = &intTest; //a non-const pointer to const data.
MyClass * const pointerTest = &intTest; //a const pointer to non-const data.

无论const出现在type之前还是之后(int)。

因此

const int const* pointerTest

翻译成

const int* pointerTest

既然放了两次const什么都不做。

物质是const*的顺序,所以在你的情况下:

-第一个是const int pointer

const int const* pointerTest = &intTest;

-第二个是const int const pointer:(因为const*之后)

const int* const pointerTest2 = &intTest;

因此,您无法更改指针并收到错误。