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;
}
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With