如何正确使用类对象

时间:2019-04-12 22:35:48

标签: visual-c++

我无法比较(列表[0] .getOwned()==否) 我也无法使用(list [0] .setOwned(true);)

来实际更改数据。
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
using namespace std;


class Weapon
{
private:
    bool owned; // bool for item owned
    string item; // string for Item 1
    string sound; // string for Sound

public:
    Weapon(bool O, string I, string S)
    {
        bool owned = O;
        string item = I; 
        string  sound = S;
    }
    Weapon()
    {
        bool owned = false;
        string item = "no name";
        string sound = "no name";

    }
    void setOwned(bool O)
    {
        owned = O;
    }

    void setItem(string I)
    {
        item = I;
    }

    void setSound(string S)
    {
        sound = S;
    }

    bool getOwned()
    {
        return owned;
    }

    string getItem()
    {
        return item;
    }

    string getSound()
    {
        return sound;
    }

};

int main()
{
    const int NUM_WEAPONS = 5;
    Weapon list[NUM_WEAPONS];
    list[0] = Weapon(false,"Sword", "Shing");
    list[1] = Weapon(false, "Axe", "Fwump");
    list[2] = Weapon(false, "Dagger", "Tsk");
    list[3] = Weapon(false, "Tiger Mount", "Roar");
    list[4] = Weapon(false, "Shield", "Thud");

  if (list[0].getOwned() == false)
{
   cout << "You've purchased a Sword" << endl;
   list[0].setOwned(true);
    cash = cash - p1;

}
else if (list[0].getOwned() == true)
{
    cout << "You already own this weapon" << endl;
}

}

我希望list [0] .getOwned()== false进行比较,并通过if语句将其设置为true,这样您就无法“再次购买”。 它没有任何作用,是我错误地使用了类对象还是完全缺少了其他东西。

1 个答案:

答案 0 :(得分:0)

Weapon构造函数声明并初始化一个名为owned的局部变量。它不会初始化成员变量this->owned。然后,您的程序将通过访问未初始化的对象来显示未定义的行为。