When I call a class, it is not recognizing a string

I am learning classes now, and for some reason, when I call a class, it is not recognizing my string.

If I put both my new class in main.cpp (in code::blocks), then it works, but when I put the class(called monster) into monster.h, it tells me that 'string' has not been declared(error on line 14 of monster.h). What am I doing wrong?

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include "monster.h"

using namespace std;

int main()
{
    Monster reptar;
    reptar.setHealth(100);
    reptar.setWeight(185);
    reptar.setName("Shane");
    cout << "<------->" << endl;
    cout << "  " << reptar.getName() << endl << "  " << reptar.getHealth() << endl << "  " << reptar.getWeight() << endl;
    cout << "<------->";
    return 0;
}



monster.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#ifndef MONSTER_H
#define MONSTER_H
#include <iostream>
#include <string>


class Monster
{
    public:
        void setHealth(int x){ health = x; }
        int getHealth() { return health; }
        void setWeight (float x) { weight = x; }
        float getWeight () {return weight; }
        void setName (string x) {name = x; }
        string getName () {return name;}

    private:
        int health;
        float weight;
        string name;
};


#endif // MONSTER_H



Last edited on
use

using namespace std;

in your .h file too :D, or add std:: before every string.
Last edited on
ahhhh that worked thank you!! I have seriously been struggling with this for the entire day!

What is 'using namespace std;'? Is there an easy explanation?
C++ has "namespaces" which house identifiers (like "string" or "cout", or anything else that you get from including a normal header). The reason it does this is to prevent name conflicts. For example if you write a function named 'swap' it might be a conflict because there already is a function named swap.

So to avoid that conflict, you have to specify which swap you want to use. You do this by specifying which namespace it's in. swap, string, etc are all in a namespace called "std". So their full name is "std::string" and "std::swap".

Now... when you put using namespace std; you are taking everything in the std namespace and dumping it into the global namespace. This has the advantage of reducing the typing you have to do, because now you can use the shorter string instead of the full std::string. However it has a disadvantage because it basically completely removes the namespace, opening up possibilities for conflicts.
Topic archived. No new replies allowed.