5

My simple class won't compile in Visual Studio. It worked before I added the string company member and the getter method getCo() to it. I think I need to put #include the string standard library somewhere but I am not sure where. Any idea where? In my header file, I have:

#pragma once
#ifndef ENGINEER_H_
#define ENGINEER_H_

class engineer {
    int years;
    string company;
public:
    engineer(int years);
    ~engineer(void);
    int getYears();
    string getCo();
};

#endif ENGINEER_H_

And in my CPP file for the definition of the class, I have:

#include "StdAfx.h"
#include "engineer.h"

engineer::engineer(int y, string c){
    years = y;
    company = c;
}

engineer::~engineer(void) {
}

int engineer::getYears() {
    return years;
}

string engineer::getCo() {
    return company;
}
Animal Rights
  • 9,107
  • 6
  • 28
  • 40

2 Answers2

19

Put it in the header file, and prefix your usage of string with the namespace std.

Header:

#include <string>

class engineer
{
   std::string company;
};

In the implementation file (.cpp) you can prefix the names or have a using directive.

Implementation:

using namespace std;  // using directive, no longer need to use std::

Avoid putting the using directive in a header file, as that pollutes the global namespace and can cause problems with naming collisions in other libraries you may wish to use.

Chad
  • 18,706
  • 4
  • 46
  • 63
3

Put it in the header file, after the include guards:

#include <string>
using std::string;

This way, it will also be available for your cpp file, and you don't have to include it again.

BTW, the #pragma once and #ifndef ENGINEER_H_ serve the same purpose. You can have only one of them. Code generated by VC use the #pragma, which is shorter and doesn't add a definition, so that's what I'd use (no harm if you leave both, though).

Eran
  • 21,632
  • 6
  • 56
  • 89
  • 2
    Putting a `using namespace` directive in a header file is never a good idea. – Chad Sep 16 '11 at 20:17
  • @Chad, there's no `using namespace` here, just `using std::string`. I agree bringing the complete namespace in would be a bad idea, but since string is so commonly used, I doubt `using std::string` is going to cause anyone trouble. – Eran Sep 16 '11 at 20:30
  • why is it a bad idea to put 'using namespace' in a header file? – Animal Rights Sep 16 '11 at 23:20
  • "You should definitely NOT use using namespace in headers for precisely the reason you say, that it can unexpectedly change the meaning of code in any other files that include that header." -> https://stackoverflow.com/questions/5849457/using-namespace-in-c-headers – Karol Król Aug 19 '19 at 15:54