c++ - 使用 g++ : 'malloc' was not declared in this scope 时出错

标签 c++ namespaces g++ malloc

我正在练习 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/

相关文章:

xml - 为什么这个 XSLT 输出这个 XML?我正在使用 XslCompiledTransform

c++ - Emacs - 覆盖缩进

c++ - Arduino:如何向任何文本框或记事本显示 Serial.print 值

c++ - 数学计算和 setprecision() 函数有问题

C++11 std::atomic<T> 复制构造函数的线程安全

c# - 如何解决 BlazorServer 默认项目解决方案中的命名空间错误(VisualStudio 代码)

c++ - 如何在 C++11 中使用随机生成器作为类成员

c++ - 用于创建静态库的链接库

c++ - 为什么包含未使用的 bool 会影响 char 的引用?

c++ - "Recompile with -fPIC"- 但使用 -fPIC 重新编译无法修复