Casting from void* to an object array in c++
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.
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
void * pointer = a;
a
is implicitly converted to a pointer to its first element, and that is then casted to void*
.
From that, you cannot have the array back, but you can get the pointer to the first element:
A* b = static_cast<A*>(pointer);
(Note: casting between pointers to unrelated types requires a reinterpret_cast
, except for casts to void*
which are implicit and from void*
to any other pointer, which can be done using a static_cast
.)
Perhaps you mean to do
memcpy(b, (A**)pointer, sizeof b);
?
A static_cast
version is also possible.
精彩评论