我想指针存储在一个数据结构中的不同类的对象(如阵列,HashMap的...)。据this answer我出来使用无类型指针void*
和运营商&*(ClassName*)
为指针类型重铸以下解决方案:存储指针
#include <stdio.h>
class ClassA{ public: int a; };
class ClassB{ public: double b; };
class Storage{
public:
int n;
void** store;
Storage(int n_){ n = n_; store = new void*[n]; };
};
Storage s(5);
int main(){
// test store and load ClassA
ClassA a1; a1.a = 16;
s.store[ 0 ] = &a1;
ClassA* a2 = &*(ClassA*) s.store[ 0 ];
printf( " a2 %i \n", a2->a);
// test store and load ClassB
ClassB b1; b1.b = 15.1455;
s.store[ 1 ] = &b1;
ClassB* b2 = &*(ClassB*) s.store[ 1 ];
printf( " b2 %f \n", b2->b);
}
现在问题:
- 是什么不好类似
&*(ClassB*)
的类型转换除外,它不是类型安全的? - 是否有此类型转换任何性能损失?
- 有没有更好的(更好,更安全,更快)的方式如何存储指针,以在单个阵列中不同类的不同的对象?
啊,我想通了,它实际上不是有用,使其void**
因为比我现在有办法以后怎么识别存储对象的类型。最好是用模板和普通超类来做。像这样
#include <stdio.h>
#include <cstdlib>
template< class TYPE1 > class Storage{
public:
int n;
TYPE1** store;
Storage(int n_){ n = n_; store = new TYPE1*[n]; }; // Constructor
void put(int key, TYPE1* obj){ store[key] = obj; }; // save data
TYPE1* get(int key ){ return store[key]; }; // load data
};
class Parent { public: int kind; };
class ChildA : public Parent { public: int someData; ChildA(int someData_ ){ kind=0; someData =someData_; } };
class ChildB : public Parent { public: double otherData; ChildB(double otherData_){ kind=1; otherData=otherData_; } };
Storage<Parent> mixed(10);
int main(){
srand(15454);
printf(" ==== initialize by random data and radom type \n");
for(int i=0; i<mixed.n; i++){
if ((rand()&4) > 0){
int someData = rand()&0xFF;
mixed.put(i, new ChildA( someData));
printf(" i %i ChildA.someData = %i \n", i , someData);
}else{
double otherData = (rand()&0xFF)/256.0f;
mixed.put(i, new ChildB( otherData));
printf(" i %i ChildB.otherData = %f \n", i , otherData);
};
};
printf(" ==== recall stored data \n");
for(int i=0; i<mixed.n; i++){
Parent* obj = mixed.get(i);
if (obj->kind ==0){ printf(" i %i ChildA.someData = %i \n", i , ((ChildA *) obj)->someData ); }
else { printf(" i %i ChildB.otherData = %f \n", i , ((ChildB *) obj)->otherData); };
};
}
早在您感兴趣的问题的标题:“我想要做坏事”的领土。然后用**来说,“是的,真的很糟糕,没有什么能阻止我,你听到了!”。好的,寻求帮助的不协调。 –
有更好的东西,例如['的std :: tuple'](http://en.cppreference.com/w/cpp/utility/tuple)。 –
干杯和hth。 - Alf> probaly它只是缺乏我的知识。你可以说得更详细点吗。还有什么我可以做动态可分配的指针数组比**? –