Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么我可以在lambda中使用ostream cout,尽管它是';你没抓到吗?_C++_C++11_Lambda - Fatal编程技术网

C++ 为什么我可以在lambda中使用ostream cout,尽管它是';你没抓到吗?

C++ 为什么我可以在lambda中使用ostream cout,尽管它是';你没抓到吗?,c++,c++11,lambda,C++,C++11,Lambda,此lambda失败,因为我尚未捕获变量: int main() { int val = 5; auto lambda = []{ return val; }; // error: val wasn't captured. lambda(); } 但是为什么ostream虽然没有被捕获却无法工作呢 int main() { auto lambda = []{ cout << endl; }; // works } intmain() { 自动la

此lambda失败,因为我尚未捕获变量:

int main()
{
    int val = 5;
    auto lambda = []{ return val; };  // error: val wasn't captured.
    lambda();
}
但是为什么ostream虽然没有被捕获却无法工作呢

int main()
{
    auto lambda = []{ cout << endl; };  // works
}
intmain()
{

自动lambda=[]{cout这是因为
std::cout
是通过以下方式定义的(在
标题中):

#包括
#包括
#包括
#包括
名称空间标准{
外间流cin;
外部环境;
外部奥斯特雷姆塞尔;
外部奥斯特雷姆阻塞;
外用wistream-wcin;
外部输出;
外部沃克尔;
外部工作日志;
}

而您的
val
变量是本地定义的(即在函数/类的范围内)。

std::cout
是一个全局变量。它对每个人都可见。这有助于我理解
#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
  extern istream cin;
  extern ostream cout;
  extern ostream cerr;
  extern ostream clog;
  extern wistream wcin;
  extern wostream wcout;
  extern wostream wcerr;
  extern wostream wclog;
}