c++ - 如何在函数内调用命名空间?
问题描述
我的代码有些有趣和错误。
#include <iostream>
void func(){
using namespace std;
}
main(){
func(); //Here the function will introduce the (using namespace std declaration) in the code
cout << "Hello World!";
return (0);
}
编译时显示错误消息:
atizva@atizva:~/Documents/C++/Programs$ g++ -o func function_call.cpp
function_call.cpp: In function ‘int main()’:
function_call.cpp:7:2: error: ‘cout’ was not declared in this scope
cout << "Hello World!";
^~~~
function_call.cpp:7:2: note: suggested alternative:
In file included from function_call.cpp:1:0:
/usr/include/c++/7/iostream:61:18: note: ‘std::cout’
extern ostream cout; /// Linked to standard output
^~~~
我不明白为什么函数'func()'没有适当地调用标签:'using namespace std'。
解决方案
要解决此问题,您必须using namespace std;
移出func()
. 这在您当前的代码中失败的原因是该using
声明仅适用于它被调用的范围内(在这种情况下func()
)。所以一旦你退出func()
,你就失去了using namespace std;
推荐阅读
- java - 为什么 JPA 的 drop-and-create 选项不起作用
- php - Phpunit 测试,包含文件时出错
- qt - 无法在 ColumnLayout 中水平居中项目
- wordpress - WordPress中的自定义主题不显示任何内容
- python - 名称 Conte 未在 python 中定义
- c# - WPF C#游戏:延迟一行的代码延迟方法
- python - 在 macOS 上以并行模式运行 django 测试时出现段错误
- python - 创建要部署在 AWS 上的仪表板 docker 容器
- python - 如何在没有任何路径或环境相关问题的情况下通过 nextflow 在 docker 容器中运行 python 脚本?
- python - 如何从 python 字典中获取所有可能的键值对?