カスタムクラスのリストを印刷することに関して誰かが私を助けることができるかどうか疑問に思っていました(コンテナを初めて使用する)。
現在、次のように宣言された変数があります。
std::list<Item> inventory;
player と呼ばれるクラス内。
これで、クラス (プレーヤー) 内に という関数を作成しましたvoid printInventory();
。
だから私の質問は、そのリストにあるものをどのように印刷するのかということです。
私Item
のクラスには 3 つの変数が含まれています。
std::string name;
int damage;
int value;
これらの変数を出力する機能もありますvoid itemDetails();
どんな助けでも大歓迎です。
編集:
提供された回答のおかげで問題が解決したことはわかっています。ここで私がしたことは次のとおりです。
項目クラスの出力演算子をオーバーロードしました:
ostream& operator<<(ostream& os, const Item& item)
{
if (item.getTypeInt() == 0)
{
os << "Name: " << item.getName() << endl
<< "Type: " << item.getTypeString() << endl
<< "Damage: " << item.getDamage()<< endl
<< "Value: " << item.getValue() << endl;
}
else
{
os << "Name: " << item.getName() << endl
<< "Type: " << item.getTypeString() << endl
<< "HP: " << item.getHP()<< endl
<< "Value: " << item.getValue() << endl;
}
return os;
}
次に、回答の1つを使用しましたが、別の変数を宣言しないように変更しました。
void Player::printInventory()
{
for(std::list<Item>::iterator it = inventory.begin(); it!= inventory.end(); ++it)
{
cout << *it;
}
cout <<"Inventroy Printed!!"<<endl;
}