简体   繁体   English

从void *转换为c ++中的对象数组

[英]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++). 数组是C中的二等公民(因此在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* . a被隐式转换为指向其第一个元素的指针,然后将其转换为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 .) (注意:在指向不相关类型的指针之间进行转换需要reinterpret_cast ,除了转换为void* ,它们是隐式的,从void*为任何其他指针,这可以使用static_cast来完成。)

Perhaps you mean to do 也许你的意思是做

memcpy(b, (A**)pointer, sizeof b);

?

A static_cast version is also possible. static_cast版本也是可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM