我在將子類物件存盤到向量時遇到問題。我有家長班
class IngameObject
{
protected:
bool clickable = false;
};
我有二等獎
class Character : public IngameObject
{
protected:
bool clickable = true;
};
現在,我正在嘗試創建 Character 的新實體并將其傳輸到向量。我將向量定義為
std::vector<IngameObject*> objVector;
創建字符和存盤它們的代碼是
for(int i = 0; i < 1; i )
{
int a = i*32;
Character *c = new Character(this->holderTextures["texture"], sf::IntRect(a, a, 32, 32), sf::Vector2f(2*a, 10.f));
std::cout << instanceof<Character>(c) << " TEST" <<std::endl;
this->objVector.emplace_back( c );
std::cout << instanceof<Character>(this->objVector.back()) << " TEST" <<std::endl;
}
在第一種情況下,實體是字符。在 emplace_back 之后,objVector 是 IngameObject 實體的型別,并且 bool clickable 設定為 false。我做錯了什么?
EDIT Instanceof 定義為
template<typename Base, typename T>
inline bool instanceof(const T*) {
return std::is_base_of<Base, T>::value;
}
uj5u.com熱心網友回復:
將派生類存盤在 astd::vector中是正確的:問題與多型性或“將派生類存盤在向量中”無關:
#include <iostream>
#include <vector>
class IngameObject
{
protected:
bool clickable = false;
};
class Character : public IngameObject
{
protected:
bool clickable = true;
};
int main()
{
std::vector<IngameObject*> objVector;
Character *c = new Character();
objVector.emplace_back( c );
delete c;
return 0;
}
問題與你實施有關 instanceof
為了解決這個instanceof函式,你的類需要是多型的。然后,可以將指向基類的指標轉換為派生類,從而確認它是instanceof基類:
#include <iostream>
#include <vector>
class IngameObject
{
protected:
bool clickable = false;
virtual ~IngameObject() = default;
};
class Character : public IngameObject
{
protected:
bool clickable = true;
};
template<class T, class U>
inline bool instanceof(U* ptr) {
return nullptr != dynamic_cast<T*>(ptr);
}
int main()
{
std::vector<IngameObject*> objVector;
Character *c = new Character();
std::cout << instanceof<Character>(c) << " TEST" <<std::endl;
objVector.emplace_back( c );
std::cout << instanceof<Character>(objVector.back()) << " TEST" <<std::endl;
delete c;
return 0;
}
注意:要使Base多型,它需要至少有一個虛方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314627.html
