[英]List of items, in c++
我列出了項目清單,但我不知道我做錯了什么。 請糾正我並發布ideone的鏈接。 我試圖在一個數組中制作一個游戲對象列表,但它不起作用。 謝謝。
#include <iostream>
#include <stdlib.h>
using namespace std;
class item{
private:
public:
item(){
//constructor
}
int id;
};
class sword:public item{
private:
public:
int damage;
string type = "Sword";
};
class potion:public item{
private:
public:
int PlusHealth;
string type = "Potion";
};
class shield:public item{
private:
public:
int armor;
string type = "Shield";
};
int main()
{
item *v[10];
bool run = true;
int aux;
int i = 0;
while(run == true && i<10) {
cout << "1- Sword 2-Shield 3-Potion -- ";
cin >> aux;
switch(aux){
case 1: v[i] = new sword;
cout << "Sword created!\n";
break;
case 2: v[i] = new shield;
cout << "Shield created!\n";
break;
case 3: v[i] = new potion;
cout << "Potion created!\n";
break;
default: run = false;
break;
}
i++;
}
system("cls");
cout << "List of items: \n";
for(int x=0;x=i-1;x++){
cout << v[x]->type;
if(type=="Sword"){
cout << " Damage: " << v[x].damage;
} else if(type=="Shield"){
cout << " Armor: " << v[x].armor;
} else if(type=="Potion") << v[x].PlusHealth;
}
return 0;
}
你在這里打破了一些概念。
您有指向父類item
的指針向量。 您應該只使用item
類中的方法和成員。
這不是正確的實現:
for(int x=0;x=i-1;x++){
cout << v[x]->type;
if(type=="Sword"){
cout << " Damage: " << v[x].damage;
} else if(type=="Shield"){
cout << " Armor: " << v[x].armor;
} else if(type=="Potion") << v[x].PlusHealth;
}
嘗試添加如下內容:
class Item
{
public:
// A generic function for child classes to print
// their specific details.
virtual void print_details(std::ostream& out) const = 0;
};
class Sword : public Item
{
public:
void print_details(std::ostream& out) const
{
out << " Damage: " << damage << "\n";
}
};
class Shield : public Item
{
public:
void print_details(std::ostream& out) const
{
out << " Armor: " << armor << "\n";
}
};
class Potion : public Item
{
public:
void print_details(std::ostream& out) const
{
out << " Health: " << PlusHealth << "\n";
}
};
//...
for (unsigned int x = 0; x < v.size(); ++x)
{
cout << "\n"
<< v[x]->type
<< "\n";
// Get the child to print the specifics.
v[x]->print_details(cout);
}
關鍵是您只能直接訪問item
方法和成員。 您可以為特殊的行為創建子類需要實現的item
方法。 在上述情況下,打印具體細節。
item
基類包含每個子item
通用方法和成員。 保持概念通用並記住item
的容器應該被通用對待。
謝謝!,但是如果我想從基類訪問派生類的 set 和 get 函數? 我一般怎么能做到這一點? 因為我對每個項目都有不同的屬性
示例: v[1].setPlusHealth 它有效,因為 v[1] 是一種葯水,但 v[1].setArmor 它不起作用,因為它不是盔甲。 我怎么能這樣做?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.