Strange error in class c++

Asked

Viewed 54 times

1

I have the following code:

#include <iostream>
using namespace std;
class guns{
public:
    string name;
    int ammo;
    void reload(){
        ammo = pente;
    }
    void shoot(){
        ammo -= 1;
    }
private:
    int pente = ammo;
};
int main(){
guns fuzil;
fuzil.name = "M-16";
fuzil.ammo = 50;
cout << "O fuzil " << fuzil.name << " tem " << fuzil.ammo << endl;
fuzil.shoot();
fuzil.shoot();
cout << "ammo: " << fuzil.ammo << endl;
fuzil.reload();
cout << "carregado: " << fuzil.ammo;
}

The exit is:

O fuzil m16 tem 50
ammo: 48
carregado: 31

Because when Reload() is executed 'Ammo' has the bizarre value 31?

1 answer

1


Work with builders, the problem is that when you declared your variable, it builds itself without value because you had no constructor method for it. When I went to compile your program and debugged pente he returned me 0.

With the constructor class you pass all attributes at the time of class distance and already assign to itself, I added the following lines:

 guns(string _name,int _ammo)
:name(_name),ammo(_ammo),pente(_ammo){}

In it, you are creating a constructor that asks for a string(name) and an int(Ammo) and right after, assigns the class, thus being the value of the pente shall be allocated immediately after the value of ammo be assigned as well. Follow the final result:

#include <iostream>
using namespace std;
class guns{
public:

    guns(string _name,int _ammo):
    name(_name),ammo(_ammo),pente(_ammo){}

    string name;
    int ammo;
    void reload(){
        ammo = pente;
    }
    void shoot(){
        ammo -= 1;
    }
private:
    int pente = ammo;
};

int main(){
    guns fuzil("M-16",50);
    cout << "O fuzil " << fuzil.name << " tem " << fuzil.ammo << endl;
    fuzil.shoot();
    fuzil.shoot();
    cout << "ammo: " << fuzil.ammo << endl;
    fuzil.reload();
    cout << "carregado: " << fuzil.ammo;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.