さまざまな種類のデータを配列またはベクトルに格納しようとしています。これまでのところ、各オブジェクトへのポインターとしてベクターに格納される基本クラスを使用してこれを行ってから、キャストと入力してデータを取得します。これは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;
}
私はおそらくここでいくつかの記念碑的な誤りを犯していますが、これまで読んでくれてありがとう:)どんな助けもありがたいです、そして建設的な批判もあります!