c++ 使用声明和函数重载

标签 c++

  1 #include <iostream>
  2 
  3 namespace primerlib {
  4     void compute() { std::cout << "primerlib::print()" << std:: endl; }
  5     void compute(const void *p) { std::cout << "primerlib::print(const void *p)" << std:: endl; }
  6 }
  7 
  8 //using primerlib::compute;
  9 //using namespace primerlib;
 10 void compute(int a) { std::cout << "::compute(int)" << std:: endl; }
 11 void compute(double d, double dd=3.4) { std::cout << "primerlib::compute(d, d)" << std:: endl; }
 12 void compute(char* p, char* p1 = 0) { std::cout << "primerlib::compute(char*, char*)" << std:: endl; }
 13 
 14 int main(void)
 15 {
 16     using primerlib::compute;
 17     //using namespace primerlib;
 18     compute(0);
 19     return 0;
 20 }

输出:

primerlib::print(const void *p)

我的问题是为什么它没有调用全局 compute(int) 一个?如果我在第 17 行使用 using 指令,它将调用 compute(int) 一个。非常感谢您的帮助。

最佳答案

那是因为using namespace Xusing X::Y 的工作方式不同。当您使用 using namespace X 时,名称查找期间会考虑该 namespace 中的所有内容。考虑以下示例:

namespace A
{
    void foo(int){}
}

namespace B
{
    void foo(int){}
}

using namespace A;
using namespace B;

int main()
{
    foo(1);
}

在这里,AB 成员都将在名称查找期间被考虑,您将有 重载 foo(int) 的调用不明确 错误,因为编译器无法决定使用这两个函数中的哪一个,因为它们是相同的。 using X::Y 语法就是为了解决这个问题。当你使用它时,你告诉编译器只使用在 X 命名空间中找到的 Y,而不考虑其他任何东西。让我们将它添加到上面的示例中:

namespace A
{
    void foo(int){}
}

namespace B
{
    void foo(int){}
}

using namespace A;
using namespace B;


int main()
{
    using A::foo;  
    foo(1);
}

这里我们告诉编译器使用在 A 命名空间中找到的 foo 的实例,并忽略任何其他 foo范围。因此,在您的示例中,您告诉编译器仅使用 primerlib::compute,如果您想访问来自全局范围的函数,并调用 compute(int)

关于c++ 使用声明和函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32265938/

相关文章:

c++ - std::map emplace/insert 正在插入的移动值

c++ - 'a' <= string[i] 是什么意思?

c++ - 如果是指针,则启用模板

c++ - C++17 中纯虚函数的主体?

c++ - LNK2019 : unresolved extrenal symbol when using std::ifstream

c++ - 编译时出现 make_unique 错误

c++ - 使用带有 Ifstream 的 Getline 缺少数据行

c++ - 除法作为乘法和 LUT ?/fast float 除法倒数

c# - 调试从 C# 项目调用的 C++ DLL

c++ - C++ 如何保持 const 值?