在 c++ 中从 void* 转换为对象数组
我在让它工作时遇到问题,
class A {
public:
A(int n) {
a = n;
}
int getA() {
return a;
}
private:
int a;
};
int main(){
A* a[3];
A* b[3];
for (int i = 0; i < 3; ++i) {
a[i] = new A(i + 1);
}
void * pointer = a;
b = (A* [])pointer; // DOESNT WORK Apparently ISO C++ forbids casting to an array type ‘A* []’.
b = static_cast<A*[]>(pointer); // DOESN'T WORK invalid static_cast from type ‘void*’ to type ‘A* []’
return 0;
}
而且我无法使用泛型类型来满足我的需要。
提前致谢。
I'm having problems getting this to work,
class A {
public:
A(int n) {
a = n;
}
int getA() {
return a;
}
private:
int a;
};
int main(){
A* a[3];
A* b[3];
for (int i = 0; i < 3; ++i) {
a[i] = new A(i + 1);
}
void * pointer = a;
b = (A* [])pointer; // DOESNT WORK Apparently ISO C++ forbids casting to an array type ‘A* []’.
b = static_cast<A*[]>(pointer); // DOESN'T WORK invalid static_cast from type ‘void*’ to type ‘A* []’
return 0;
}
And i can't use generic types for what i need.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
数组在 C 中是二等公民(因此在 C++ 中也是如此)。例如,您无法分配它们。并且很难将它们传递给函数而不降级为指向其第一个元素的指针。
在大多数情况下,指向数组第一个元素的指针可以像数组一样使用 - 除非您不能使用它来获取数组的大小。
当您编写时,
a
会隐式转换为指向其第一个元素的指针,然后将其转换为void*
。由此,您无法取回数组,但可以获取指向第一个元素的指针:(
注意:在指向不相关类型的指针之间进行转换需要
reinterpret_cast
,除了转换为void*
是隐式的,从void*
到任何其他指针,这可以使用static_cast
来完成。)Arrays are second-class citizen in C (and thus in C++). For example, you can't assign them. And it's hard to pass them to a function without them degrading to a pointer to their first element.
A pointer to an array's first element can for most purposes be used like the array - except you cannot use it to get the array's size.
When you write
a
is implicitly converted to a pointer to its first element, and that is then casted tovoid*
.From that, you cannot have the array back, but you can get the pointer to the first element:
(Note: casting between pointers to unrelated types requires a
reinterpret_cast
, except for casts tovoid*
which are implicit and fromvoid*
to any other pointer, which can be done using astatic_cast
.)也许你想做什么
?
static_cast
版本也是可能的。Perhaps you mean to do
?
A
static_cast
version is also possible.