I am practicing g++ to compile my code yet the error "malloc was not declared in this scope" keeps emerging at the beginning. The pieces of my code related to this error looks like:
/*------Basic.h--------*/
using namespace std;
/*------A.h------------*/
class A{
private:
double* _data;
public:
A(int N);
}
/*------A.cpp----------*/
A::A(int N){
_data=(double*)malloc(N*sizeof(double));
}
This problem never emerges when I use Microsoft Virtual Stdio. I therefore tried to add a line
#include <stdlib.h>
to Basic.h, and the error disappears. Now I am wondering why this kind of thing happens. Hasn't "namespace std" already include stdlib.h? Thanks a lot.
Best Answer
Namespaces and include files are two totally different things. You need to
or, equivalently,
in order to get access to the declarations in that header file.
Your using-declaration
on the other hand, means that you can use identifiers that are part of the namespace
std
, i.e. that were declared insidewithout prepending
std::
each time.For example, if you
include <string>
, you can use the data typestd::string
, but if you also addusing namespace std;
, you can use that data type simply asstring
.Note, however, that
malloc
is not defined inside any namespace, so in order to use that, you need only to includestdlib.h
.Note For the difference between
stdlib.h
andcstdlib
, see here.