我需要知道是否真的有办法轻松完成这项工作。这只是我想要做的一个例子......
void* ptr;
ptr = new Foo;
((Foo*)ptr)->member1 = some_val;
((Foo*)ptr)->member2 = some_val;
((Foo*)ptr)->member3 = some_val;
((Foo*)ptr)->member4 = some_val;
((Foo*)ptr)->member5 = some_val;
((Foo*)ptr)->member6 = some_val;
因为ptr是一个void *,无论如何我可以暂时改变ptr类型,这样我每次都不必使用它来使用它吗?
我不能只创建另一个Foo类型的指针,因为ptr在别处使用并且需要是void类型。所以我想,暂时让它成为Foo类型,以避免我必须做的所有混乱的演员。
**似乎有些人感到困惑... ptr必须保持类型无效,因为在程序中它的使用方式如下: -
void* ptr;
switch (bar)
{
case 1:
ptr = new Foo;
((Foo*)ptr)->member1 = some_val;
((Foo*)ptr)->member2 = some_val;
((Foo*)ptr)->member3 = some_val;
((Foo*)ptr)->member4 = some_val;
((Foo*)ptr)->member5 = some_val;
((Foo*)ptr)->member6 = some_val;
case 2:
ptr = new Doo;
...
case 3:
ptr = new Scooby;
...
因此,ptr必须保持类型为void。我只是想知道是否有一种临时的方法将ptr转换为另一种类型,所以请避免使用...
答案 0 :(得分:1)
我不明白为什么你不能创建一个时间指针:
void* ptr;
ptr = new Foo;
{
Foo *pt=(Foo*)ptr;
pt->member1 = some_val;
pt->member2 = some_val;
pt->member3 = some_val;
pt->member4 = some_val;
pt->member5 = some_val;
pt->member6 = some_val;
}
void *t=ptr; // the original ptr
有时我会使用:
Foo &f= *((Foo*)ptr);
f.member1 = some_val;
f.member2 = some_val;
f.member3 = some_val;
f.member4 = some_val;
f.member5 = some_val;
f.member6 = some_val;
答案 1 :(得分:0)
编辑:此答案已过时,因为原始问题已被修改。
您可以使用:
Foo* ptr;
ptr = new Foo;
ptr->member1 = some_val;
ptr->member2 = some_val;
ptr->member3 = some_val;
或
void* ptrFromElseWhere;
Foo* ptr = static_cast<Foo*>(ptrFromElseWhere);
ptr->member1 = some_val;
ptr->member2 = some_val;
ptr->member3 = some_val;