Home > database >  cout a string from class outputs a "nan"
cout a string from class outputs a "nan"

Time:07-25

I created a class that holds the information about a character in a game. I also created a constructor for it. But when I cout a string or a float from the class, it outputs a "nan" or a weird and long number or just nothing. look at the code:-

#include <iostream>
#include <conio.h>
#include <string>
#include <windows.h>

using namespace std;

class Character {
public:
    string type;
    string name;
    float HP;
    float MP;
    float str;
    float def;
    float agility;
    int LVL;

    Character(string atype, string aname, float aHP, float aMP, float astr, float adef, float aagility, int aLVL){
        string type = atype;
        string name = aname;
        float HP = aHP;
        float MP = aMP;
        float str = astr;
        float def = adef;
        float agility = aagility;
        int LVL = aLVL;
    }
};

int main()
{

    Character war("Warrior", "Achilles",    100, 30,  50,  35,    30,     1);

    cout << war.type << endl;
    cout << war.name << endl;
    cout << war.HP << endl;
    cout << war.MP << endl;
    cout << war.str << endl;
    cout << war.def << endl;
    cout << war.agility << endl;
    cout << war.LVL << endl;
    cout << "Test String" << endl;

    return 0;
}

and the output is:-

//nothing
//nothing again
1.08418e-038
1.08418e-038
4.15749e 033
4.19234e-033
nan
36
Test String

Please help!

CodePudding user response:

Character(string atype, string aname, float aHP, float aMP, float astr, float adef, float aagility, int aLVL){
    string type = atype;
    string name = aname;
    float HP = aHP;
    float MP = aMP;
    float str = astr;
    float def = adef;
    float agility = aagility;
    int LVL = aLVL;
}

should be

Character(string atype, string aname, float aHP, float aMP, float astr, float adef, float aagility, int aLVL){
    type = atype;
    name = aname;
    HP = aHP;
    MP = aMP;
    str = astr;
    def = adef;
    agility = aagility;
    LVL = aLVL;
}

Your version creates new variables which hide the class members you are trying to assign to! That's why they have garbage values.

The preferred way to do this however is to use an initialiser list

Character(string atype, string aname, float aHP, float aMP, float astr, float adef, float aagility, int aLVL)
    : type(atype)
    , name(aname)
    , HP(aHP)
    , MP(aMP)
    , str(astr)
    , def(adef)
    , agility(aagility)
    , LVL(aLVL)
{
}
  • Related