Help debugging classes.

Hello.
When i compile the following code it runs just fine.

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
29
30
31
32
  #include <iostream>
#include <string>
using namespace std;

class MyClass
{
    public:

void SetN(string nm)
{
    name = nm;

}

string GetN()
{
return name;
}

string name;

};

int main()
{
  MyClass obj;

 obj.SetN("ali");
 cout<<obj.GetN();
    return 0;
}


But when i create separate header and source files i get a compilation error:

My Header file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef MYCLASS_H
#define MYCLASS_H


class MyClass
{
    public:
MyClass();
void SetN(string nm);
string GetN();
string name;


};

#endif // MYCLASS_H 


My Source file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "MyClass.h"
#include <iostream>
#include <string>
using namespace std;

MyClass::MyClass()
{
}

void MyClass::SetN(string nm)

{
    name = nm;

}

string MyClass::GetN(){
return name;

}


My Main:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include "MyClass.h"
#include <string>
using namespace std;

int main()
{
  MyClass obj;

 obj.SetN("John");
 cout<<obj.GetN();
    return 0;
}


I get an error saying:('string' has not been declared) and ('string' does not name a type)
Your header file contains a class that uses string.

So put #include <string> in your header file.

Then, do NOT put using namespace std; in your header file (or anywhere, really).

Put using std::string; or prefix every string with std::
Last edited on
I did so, still getting the same errors. -_-
Last edited on
I disagree.

Either you did not do so, or you are not getting the same errors.
Sorry, it was my bad and thank you, it worked!
I added #include <string> to my header file and replaced using namespace std with using std::string;
Should i always use using std::string in my header files?
Definitely do not ever put using namespace std; in header files.

Whether you want to put
using std::string;
or just put
std::
before every use of string is far less important, and you can just do whatever is easier for you.
using std::string; is less bad than using namespace std; in a header, but I would advise avoiding putting any using statements at all in headers. Otherwise, you're forcing any code that uses your header, to pull things into the global namespace, without any consideration of what problems that might cause for the code including that header.

Topic archived. No new replies allowed.