我想存儲數組或矢量中的各種不同類型的數據。到目前爲止,我正在通過使用基類來完成這一任務,該基類將作爲指向每個對象的指針存儲在向量中,然後鍵入cast以獲取數據。這對int很有用,但其他任何類型的數據都會引發訪問衝突異常。存儲各種類型的載體
很抱歉,如果我的解釋是不是很好,這是我帶註釋的代碼,我希望能幫助:
//Base class
class MenuProperty
{
private:
std::string Name;
public:
MenuProperty(std::string Name) : Name(Name) {};
~MenuProperty() {};
std::string GetName();
};
//Typed class used to store data
template<class T>
class TMenuProperty : public MenuProperty
{
private:
T Data;
public:
TMenuProperty(std::string Name, T Data) : MenuProperty(Name), Data(Data) {};
T GetData()
{
return this->Data;
}
};
//Class with no type and data pointer to retrieve data
class cpMenuProperty : public MenuProperty
{
private:
VOID* Data;
public:
cpMenuProperty(std::string Name) : MenuProperty(Name) {};
VOID* GetPointer()
{
return this->Data;
}
};
希望這是意義一些外表,這裏是我的測試代碼:
int main()
{
TMenuProperty<double> fP("Test2", 33.7354); //Create instance of property
MenuProperty* fMP = &fP; //Make a pointer to the object
cpMenuProperty* Test; //Make a pointer to the retrieving
//object
std::vector<MenuProperty*> Vec;
std::vector<MenuProperty*>::iterator it;
Vec.push_back(fMP);
it = Vec.begin();
Test = static_cast<cpMenuProperty*>(*it); //Cast the first object in the list
//list to the same type as the
//retrieveing object
double Data = *(double*)Test->GetPointer(); //Dereference and access, this is
//where the exception is thrown
std::cout << Data;
int Ret;
std::cin >> Ret;
}
我可能做一些在這裏巨大的錯誤,但感謝您抽出時間來迄今閱讀:)任何幫助表示讚賞,並提出建設性意見呢!
TMenuProperty fP(「Test2」,33.7354);將其更改爲TMenuProperty * fP = new TMenuProperty fP(「Test2」,33.7354); –
見http://stackoverflow.com/questions/7804955/heterogeneous-containers-in-c – learnvst