为什么 const MyClass const* 无效
Why is const MyClass const* not valid?
我对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;
因此,您无法更改指针并收到错误。
- 将 const 转换为 const char* 无效,我该如何解决?使用 gcc7 时失败
- 为什么在引用指针时将 const 放在 & 符号的左侧有效,而在右侧则无效?
- C++ 错误:由于 swprintf 而从 'int' 到 'const wchar_t* 的转换无效
- 类型"int"和"const char [15]"到二进制"运算符<<"的无效操作数^
- 错误:从'void*'到'const uint8_t* {aka const unsigned char*}'的转换无效 [-允许]
- 错误:从 'char' 到 'const char' [-允许] strcat(加密,密钥[i])的转换无效;
- 返回对象时从'const DList<int>* const'到 'DList<int>*' [-fallowive] 的转换无效
- 我收到一个错误无效的操作数,类型为 const char [42] 和二进制"运算符+"的双倍数
- 错误:数组下标的类型"const bool[int]"无效
- constexpr 链表 - 从 const X* 到 X* 的转换无效
- 在这个简单函数中从'char'到'const char*'的无效转换
- 'const char [26]' 和 'LPSTR ' 类型的无效操作数
- C++从 'const char*' 到 'char*' Arduino Uno 的无效转换
- 在 C++ 中从 'const float*' 到 'float*' 的转换无效
- 如何修复C++中的"错误:从'int'到'const char*'[-fallowive]的无效转换?
- 将文本文件读取为 const char* 有时有效,有时无效
- C++:"错误:类型'const char*'和'const char [28]'的操作数无效到二进制'ope
- C++错误:从"char"到"const char*"的转换无效[-允许]
- 什么是const无效
- 为什么 const MyClass const* 无效