Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where do i include the string library in my C++ header file

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;
}
like image 971
iamdtang Avatar asked Sep 16 '11 20:09

iamdtang


2 Answers

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.

like image 65
Chad Avatar answered Nov 19 '22 06:11

Chad


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).

like image 27
eran Avatar answered Nov 19 '22 05:11

eran