Hello, I’m quite new to c++ and until now I’ve only created one .cpp file that contains a class definition and the code that using it.
I’ve now tried to separate out into a header file ‘dayType.h’ that contains the prototype for the class , the implementation file ‘dayTypeImp.cpp’ that contains the member function definitions (as suggested in books I’ve read) and lastly the main program main.cpp. All the files are called out in the solution explorer window in the correct positions in the IDE and I know the program compiled and ran ok when it was only in one file main.cpp.
When I try to build it , it reports that there is a syntax error in the header file and the string class is not recognised.
I’m convinced I’ve missed some small detail like I’ve not called out another header file somewhere or some key word or instruction somewhere?. I've included the header files that take care of using the 'string' class in the implementation file the main program so i'm not sure why it's reporting this ???
or do i put an #include in the header for the string usage in this file?
i missed the statement 'using namespace std' from my header file!!
You should never have the statement usingnamespace std; in a header file. It pollutes the global namespace for everyone who uses that header.You should also really try to avoid it everywhere else too.
I understand what you're saying and I don't want to develop any bad working practises, but what was in this statement that made my program finally work?
When you include a standard library with #include <string> you need to prefix everything in that library with its namespace specifier std::
1 2 3
#include <string>
std::string str; // prefix with std::
In order to avoid typing std:: all the time some people put the usingnamespace std; statement in. What that does is copy all the symbols from the library into the global namespace. That means you can access them as globals:
1 2 3 4
#include <string>
usingnamespace std;
string str; // no need to use std::
The problem is the fact that it contaminated the global namespace. If you do that in a header file it will contaminate the global namespace for everyone that includes the header. This can cause subtle errors and break code in subtle hard to find ways.