> I did not know you cannot use namespaces in header files!
I didn't say you cannot.
I said it's a supremely BAD idea to do so.
> I still have to figure out why std:: namespaces are needed in a header file that uses a library.
Because everything in modern C++ is in one namespace or another.
Here is an example program using namespaces.
Code:
#include <iostream>
#include <fstream>
void foo ( ) {
std::cout << "This is foo\n";
}
namespace cprog {
int bar ( ) {
return 42;
}
}
int main ( ) {
std::fstream is; // fstream is in the std:: namespace
foo(); // foo is in the global namespace
int x = cprog::bar(); // bar is in the cprog namespace
std::cout << "Bar=" << x << "\n";
}
And the same with using namespace
Code:
#include <iostream>
#include <fstream>
using namespace std;
void foo ( ) {
cout << "This is foo\n";
}
namespace cprog {
int bar ( ) {
return 42;
}
}
int main ( ) {
fstream is; // fstream is in the std:: namespace
foo(); // foo is in the global namespace
int x = cprog::bar(); // bar is in the cprog namespace
cout << "Bar=" << x << "\n";
}
In short, "using namespace std;" is a lazy one line sop to make ancient C++ programs somewhat usable in modern C++ (when everything moved from the global namespace to the std namespace).
While you're writing toy programs that depend only on the standard library, it's somewhat harmless.
But when you get to writing code importing namespaces from several external libraries, then knowing how to use namespaces properly becomes far more important.
So if you want to save some future grief, stop being lazy and learn to write std:: in front of all the references to the standard library.
There is a half-way house approach.
Code:
#include <iostream>
#include <fstream>
// I use std::cout a lot, so just make this one thing a bit
// easier on the eye and the fingers.
// Everything else would need to be qualified with std::
using std::cout;
void foo ( ) {
cout << "This is foo\n";
}
namespace cprog {
int bar ( ) {
return 42;
}
}
int main ( ) {
std::fstream is; // fstream is in the std:: namespace
foo(); // foo is in the global namespace
int x = cprog::bar(); // bar is in the cprog namespace
cout << "Bar=" << x << "\n";
}
> After entering in the .h and .cpp files main.cpp is no longer needed so I remove it ...
Make sure to save the project.