I’m just starting to learn about C++ classes, and I had a question regarding how to check a variable for each object without cycling through them using if-statements.
Here is my code:
#include <iostream>
using namespace std;
string ans;
class Weapon {
public:
string name;
int damage;
bool isCurrentWeapon;
public:
Weapon(string n, int d, bool iCW){
name = n;
damage = d;
isCurrentWeapon = iCW;
}
};
int main()
{
Weapon sword("Sword",30,true);
Weapon dagger("Dagger",10,false);
cout<<"Welcome to the Weapon Shop! Your current weapon is: " XXXXXXX
return 0;
}
My question is how would I replace the XXXXXXX with the current weapon? I’d like to somehow check out of ALL of the objects in the class, which one has isCurrentWeapon
set to true
. And I’d like to do this without using if-statements to individually check each weapon.
I tried to use a static variable, but I decided that that probably wasn’t right, as each instance of Weapon
has the variable isCurrentWeapon
.
Thanks!
(If there is a better title for this question please edit it – I just couldn’t think of a way to describe it better.)
>Solution :
isCurrentWeapon shouldn’t be a member of the class. You should instead keep a pointer outside the class that points to whichever weapon is the current one.
#include <iostream>
using namespace std;
string ans;
class Weapon {
public:
string name;
int damage;
public:
Weapon(string n, int d, bool iCW){
name = n;
damage = d;
}
};
Weapon* currentWeapon;
int main()
{
Weapon sword("Sword",30,true);
Weapon dagger("Dagger",10,false);
currentWeapon = &sword;
cout<<"Welcome to the Weapon Shop! Your current weapon is: " << currentWeapon->name;
return 0;
}