从void *的铸造在C对象数组++ [英] Casting from void* to an object array in c++

查看:162
本文介绍了从void *的铸造在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.

先谢谢了。

推荐答案

数组在C中二等公民(以及在C ++中)。例如,你不能为它们分配。而且很难将它们传递给函数没有他们降低到一个指向他们的第一个元素。结果
一个指向数组的第一个元素都可以在大多数情况下可以使用像阵列 - 除了你不能用它来获取数组的大小。

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.

当你写

void * pointer = a;

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);

(注:指向不相关的类型之间的铸造需要一个 reinter pret_cast ,除了强制转换为无效* 这是隐含的,并从无效* 为任何其他指针,这是可以做到用一个的static_cast

(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.)

这篇关于从void *的铸造在C对象数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆