const T* vs typedef
const T* vs typedef
以下代码在visual studio 2012中无法为我编译:
//1. Define struct
struct TestList
{
...
};
//2 define a pointer to 1. struct as typedef
typedef TestList * TestListPtr;
//3. use it latter on in the code as follows:
const TestList* p1 = 0;
const TestListPtr p2 = p1;
然后,得到这个编译错误:
error C2440: 'initializing' : cannot convert from 'const TestList *' to 'const TestListPtr'
为什么以上内容可以被视为非法语法?
还没有在其他编译器中尝试过。
编译器是对的,所有符合要求的编译器都必须拒绝。原因是声明分组不同:
CCD_ 1将CCD_ 2声明为指向常量CCD_ 3的指针。
const TestListPtr p2
声明p2
为常数TestListPtr
。TestListPtr
是指向(非常量)TestList
的指针。在没有typedef的情况下拼写p2
是这样的:
TestList * const p2 = p1;
这是一个语言语法不直观的地方。
int const i;
与相同
const int i;
当你混合指针时,有四种可能的选择:
int* p1; // You can modify both p1 and *p1
int const* p2; // You can modify p2 but not *p2
int* const p3; // You can not modify p3 but can modify *p3
int const* const p3; // You can not modify p4 or *p4
不幸的是,你可以写
int const* p2;
作为
const int* p2;
这也是你困惑的根源。
而不是使用
const TestListPtr p2 = p1;
如果你使用
TestListPtr const p2 = p1;
很清楚CCD_ 10的哪一部分是恒定的。显然const TestList * p1
1不能被修改,但是*p2
可以被修改。
相关文章:
- C++:TypeDef使用元组
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 数据成员SFINAE的C++17测试:gcc vs clang
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 正在VS调试器中监视映射条目
- Confusion: decltype vs std::function
- 将IBM Rhapsody模型集成到VS 2019中
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- typedef struct vs struct - "struct"的存储大小未知
- C++ typedef struct vs class
- 使用 vs typedef 指针到noexcept-function不一致
- const int*& vs typedef int* IntPtr
- const T* vs typedef
- C++使用别名访问嵌套类型(使用 vs typedef)
- using vs. typedef for std::vector::iterator
- 别名使用vs typedef
- C++11,使用 vs typedef,模板化