项目列表,用c ++表示

时间:2015-06-16 18:29:16

标签: c++

http://ideone.com/UlHrxS

我列出了一些项目,我不知道我做错了什么。请更正我并从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;
}

2 个答案:

答案 0 :(得分: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 s的容器应该被一般地处理。

答案 1 :(得分:0)

谢谢!,但是如果我想从基类访问set并获取派生类的函数?我怎么能这样做呢?因为我对每个项目都有不同的属性

示例:v [1] .setPlusHealth它可以工作,因为v [1]是一个药水但v [1] .setArmor它不起作用,因为它不是一个装甲。我怎么能这样做?