1. void* x;
2. x = new int [10];
3. x = static_cast<int*>(x);
4. *x = 2;
在第 4 行,我得到:error: ‘void*’ is not a pointer-to-object type
您需要定义新的指针类型。
静态强制转换了 x,但在静态强制转换后类型信息丢失,因为在声明时 x 无效*。
X将在他的一生中坚持空虚*。
这是一个工作代码示例:
void* x;
int* ptr;
x = new int[10];
ptr = static_cast<int*>(x);
*ptr = 2;
或者,您可以在同一行中分配和投射:
*(static_cast<int*>(x)) = 2;
由于任何指针(指向成员的指针和指向函数的指针除外,它们完全是其他东西(都可以隐式转换为 void 指针,因此您的第 2 行隐式将new int[10]
的结果从 int *
转换为 void *
。
同样,您的第 3 行显式将x
转换为int *
(static_cast
(,其结果被隐式转换回并存储在 x
中。 这没有净效应。 如果编译器足够聪明,它将完全忽略该语句。
您需要做的是引入另一个变量,它是指向int
的指针。
void *x;
x = new int[10];
int *y = static_cast<int *>(x);
*y = 2;
如果你真的想使用一个没有任何变量的 void 指针,那就是 int 指针,请这样做;
void *x;
x = new int[10];
*(static_cast<int *>(x)) = 2;
这是极其丑陋的,只有在特殊情况下才需要。
在实践中,除非你需要 void 指针来表示其他特定内容,否则请完全消除它。
int *x;
x = new int[10];
*x = 2;
事实上,不需要使用任何显式类型转换,这使得这也不太容易出错。