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

发布于 2024-09-27 00:15:44 字数 574 浏览 5 评论 0原文

我在让它工作时遇到问题,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

云裳 2024-10-04 00:15:44

数组在 C 中是二等公民(因此在 C++ 中也是如此)。例如,您无法分配它们。并且很难将它们传递给函数而不降级为指向其第一个元素的指针。
在大多数情况下,指向数组第一个元素的指针可以像数组一样使用 - 除非您不能使用它来获取数组的大小。

当您编写时,

void * pointer = a;

a 会隐式转换为指向其第一个元素的指针,然后将其转换为 void*

由此,您无法取回数组,但可以获取指向第一个元素的指针:(

A* b = static_cast<A*>(pointer);

注意:在指向不相关类型的指针之间进行转换需要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

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

白芷 2024-10-04 00:15:44

也许你想做什么

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

static_cast 版本也是可能的。

Perhaps you mean to do

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

?

A static_cast version is also possible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文