为什么我可以在不使用std :: getline的情况下调用getline?

Jos*_*_mr 9 c++ namespaces getline

我正在阅读C++ Primer一书并​​尝试所有代码示例.我对这个很感兴趣:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string line;
    while (getline(cin,line))
        cout << line << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在编译这段代码之前,我猜测编译会失败,因为我没有使用

while (std::getline(cin,line))
Run Code Online (Sandbox Code Playgroud)

为什么getline在全局命名空间中?据我所知,这应该只在我使用时发生

namespace std;
Run Code Online (Sandbox Code Playgroud)

要么

using std::getline;
Run Code Online (Sandbox Code Playgroud)

我在Linux Mint Debian Edition上使用g ++版本4.8.2.

Bar*_*rry 17

这是依赖于参数的查找.

不合格的查找(当你打电话getline()而不是你正在做什么时std::getline())将通过尝试进行正常的名称查找来开始getline.它什么也没找到 - 你在该名称的范围内没有变量,函数,类等.

然后,我们将查看每个参数的"关联命名空间".在这种情况下,参数是cinline,其中有种类std::istreamstd::string分别,所以它们的相关名称空间都是std.然后,我们重新命名空间内查找stdgetline找到std::getline.

还有更多细节,我鼓励您阅读我引用的参考资料.此过程另外称为Koenig查找.


Nat*_*ica 7

由于std::getline()for std::string 在头文件中定义,我不得不说依赖参数的查找正在发挥作用.


R S*_*ahu 5

当你使用时getline(cin, line),它等同于使用,getline(std::cin, line)因为你有这条线:

using std::cin;
Run Code Online (Sandbox Code Playgroud)

使用Argument Dependent Lookup(ADL),编译器能够解析该函数​​调用std::getline(std::cin, line).您可以在http://en.cppreference.com/w/cpp/language/adl上阅读有关ADL的更多信息.