【问题标题】:Why can I call getline without using std::getline?为什么我可以在不使用 std::getline 的情况下调用 getline?
【发布时间】:2015-10-14 10:16:54
【问题描述】:

我正在关注 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;
}

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

while (std::getline(cin,line))

为什么 getline 在全局命名空间中? 据我了解,这只有在我使用时才会发生

namespace std;

using std::getline;

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

【问题讨论】:

    标签: c++ namespaces getline


    【解决方案1】:

    这是argument dependent lookup

    不合格的查找(当您调用getline() 而不是std::getline() 时所做的事情)将从尝试对getline 进行正常名称查找开始。它什么也找不到——你在范围内没有具有该名称的变量、函数、类等。

    然后我们将查看每个参数的“关联命名空间”。在这种情况下,参数是cinline,它们的类型分别为std::istreamstd::string,因此它们关联的命名空间都是std。然后我们在命名空间std 中重新查找getline 并找到std::getline

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

    【讨论】:

    • 这是标准的 c++ 吗?
    • @kalkanistovinko 是的。
    【解决方案2】:

    由于std::getline()std::string is defined in the header 我不得不说Argument-dependent lookup 正在发挥作用。

    【讨论】:

      【解决方案3】:

      当你使用getline(cin, line)时,它相当于使用getline(std::cin, line),因为你有这行:

      using std::cin;
      

      使用参数相关查找 (ADL),编译器能够将该函数调用解析为 std::getline(std::cin, line)。您可以在http://en.cppreference.com/w/cpp/language/adl 阅读有关 ADL 的更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-10
        • 1970-01-01
        • 2011-10-08
        • 1970-01-01
        • 2013-03-17
        • 1970-01-01
        • 2023-03-18
        • 2019-08-25
        相关资源
        最近更新 更多