visual-c++ - 如何正确使用类对象
问题描述
我无法比较 (list[0].getOwned() == false) 我也无法用 (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,这样您就不能“再次购买”。它的作用是什么,是我错误地使用了类对象还是我完全错过了其他东西。
解决方案
Weapon
构造函数声明并初始化一个名为 的局部变量owned
。它不初始化成员变量this->owned
。然后,您的程序通过访问未初始化的对象表现出未定义的行为。