我正在尝试将各种不同类型的数据存储在数组或向量中。到目前为止,我通过使用一个基类来做到这一点,该基类将作为指向每个对象的指针存储在向量中,然后进行类型转换以获取数据。这对 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;
}
我可能在这里犯了一些巨大的错误,但感谢您花时间阅读到目前为止:) 感谢您提供任何帮助,以及建设性的批评!