首页 > 解决方案 > 如何在函数内调用命名空间?

问题描述

我的代码有些有趣和错误。

#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'。

标签: c++

解决方案


要解决此问题,您必须using namespace std;移出func(). 这在您当前的代码中失败的原因是该using声明仅适用于它被调用的范围内(在这种情况下func())。所以一旦你退出func(),你就失去了using namespace std;


推荐阅读