C++ getline() 不需要命名空间声明

C++ getline() doesn't require namespace declaration

本文关键字:命名空间 声明 不需要 getline C++      更新时间:2023-10-16

为什么getline() from header string在局部作用域内并且可以使用:

#include <iostream>
#include <string>
int main() {
    std::string str;
    getline(std::cin, str);
    std::cout << str << "n";
    return 0;
}

可以在gcc中使用。但是为什么呢?它在header string中定义,这应该要求我使用std::getline()而不是getline()

您正在经历参数依赖查找(ADL,也称为Koenig查找)。由于一个或多个参数是在std名称空间中定义的类型,因此除了在其他地方搜索之外,它还在std名称空间中搜索该函数。我建议你去看Stephan T. Lavavej的视频,了解更多关于它和名字查找的知识。