![](/img/trans.png)
[英]C++ Does derived class could inheritance Static data member and Static Member function from Base class?
[英]In C++, how does one use a class member that will hold any object derived from a base class?
在此先感謝您閱讀和/或回應。 我是編程新手。
假設我有一個Player類,該類使用ABC類型的Weapon對象作為成員。
class Player
{
private:
Weapon * mainHand; // I think this is what I want?
};
但是我想分配任何派生類的類型,例如棍棒或匕首。 如何為它分配一個新對象? 您可能已經猜到了,我希望用戶能夠做出運行時決定來“裝備”多個可用對象中的任何一個。
無論如何,我已經嘗試了大約2周的時間來通過閱讀論壇上的內容來解決問題,但我只是失敗了。 謝謝你的協助。
您可以只將mainHand
變量分配給指向從Weapon
類派生的任何類型的對象的指針。 這樣(只是示例,而不是設計建議):
void equipClub()
{
Club* someShinyClub = new Club();
mainHand = someShinyClub;
}
甚至直接:
mainHand = new Club();
之后,武器聲明的所有方法都可以從該指針訪問。 但是對於派生類的特定操作,您將需要強制轉換。
如果我理解正確,那么您希望能夠在運行時決定Player的武器選擇。
您可能已經意識到需要為此而從Weapon
派生類的事實。
您只需執行以下操作即可; 盡管我建議您找到一種更有效的方法。 ( Dagger
和Sword
類)
if(player.weaponchoice == "dagger") //assuming that the player will decide the weapon choice.
{
player.mainHand = new Dagger();
}
else if(player.weaponchoice == "sword")
{
player.mainHand = new Sword();
}
可以為武器參照指定任何擴展武器的對象。 因此,如果club擴展了Weapon,您可以編寫:
this->mainHand = new Club();
但是,mainHand只能在Weapon類中調用公共方法和受保護的方法。
this->mainHand->fire();
如果要調用特定於club的方法,則必須強制轉換它,但不必這樣做!
((Club *) this->mainHand)->beatToDeath();
請參見以下示例。 請根據您的需要采取。
class Weapon
{
public:
virtual void fire()=0;
};
class Gun:public Weapon
{
public:
void fire()override
{
std::cout<<"Gun\n";
}
};
class Rifle:public Weapon
{
public:
void fire()override
{
std::cout<<"Rifle\n";
}
};
class Player
{
public:
Player(Weapon* weapon):mainHand(weapon)
{
}
void fire()
{
mainHand->fire();
}
private:
Weapon * mainHand; // I think this is what I want?
};
int _tmain(int argc, _TCHAR* argv[])
{
Gun gun;
Rifle rifle;
Player p1(&gun);
Player p2(&rifle);
p1.fire();
p2.fire();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.