배열이나 벡터에 다양한 데이터 유형을 저장하려고합니다. 지금까지 저는 벡터에 각 객체에 대한 포인터로 저장 될 기본 클래스를 사용하여 데이터를 가져온 다음 캐스팅하여 데이터를 다시 가져옵니다. 이것은 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