我正在练习 g++ 来编译我的代码,但错误“malloc was not declared in this scope”一直在开头出现。我的与此错误相关的代码片段如下所示:
/*------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));
}
当我使用 Microsoft Virtual Stdio 时,此问题从未出现。因此,我尝试添加一行
#include <stdlib.h>
Basic.h,错误消失。现在我想知道为什么会发生这种事情。 “namespace std”不是已经包含 stdlib.h 了吗?非常感谢。
最佳答案
命名空间和包含文件是两个完全不同的东西。你需要
#include <stdlib.h>
或者,等价地,
#include <cstdlib>
为了访问该头文件中的声明。
你的using-declaration
using namespace std;
另一方面,意味着您可以使用属于命名空间 std
的标识符,即在里面声明
namespace std {
/*...*/
}
没有前置 std::
每次。
例如,如果您 include <string>
, 您可以使用数据类型 std::string
,但如果您也添加using namespace std;
,您可以将该数据类型简单地用作 string
.
但是请注意,malloc
没有在任何命名空间内定义,所以为了使用它,你只需要包含 stdlib.h
.
注意对于stdlib.h
之间的区别和 cstdlib
, 请参阅 here .
关于c++ - 使用 g++ : 'malloc' was not declared in this scope 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11425136/