【问题标题】:Function overloading between anonymous namespace and named namespace匿名命名空间和命名命名空间之间的函数重载
【发布时间】:2018-12-31 03:21:03
【问题描述】:

这是不允许的吗?谁能解释一下原因?

算法.h

namespace Algorithms
{
  int kthLargest(std::vector<int> const& nums, int k);    
}

算法.cpp

#include "Algorithms.h"
namespace
{
int kthLargest(std::vector<int> const& nums, int start, int end, int k)
{
   <implementation>
}
} // end anonymous namespace

namespace Algorithms
{
   int kthLargest(std::vector<int> const& nums, int k)
   {
      return kthLargest(nums, 0, nums.size() - 1, k);
   }
} // end Algorithms namespace

我遇到的错误是:

> /usr/bin/c++   -I../lib/algorithms/inc  -MD -MT
> lib/algorithms/CMakeFiles/algorithms.dir/src/Algorithms.o -MF
> lib/algorithms/CMakeFiles/algorithms.dir/src/Algorithms.o.d -o
> lib/algorithms/CMakeFiles/algorithms.dir/src/Algorithms.o -c
> ../lib/algorithms/src/Algorithms.cpp
> ../lib/algorithms/src/Algorithms.cpp: In function ‘int
> Algorithms::kthLargest(const std::vector<int>&, int)’:
> ../lib/algorithms/src/Algorithms.cpp:70:50: error: too many arguments
> to function ‘int Algorithms::kthLargest(const std::vector<int>&, int)’
> return kthLargest(nums, 0, nums.size() - 1, k);

【问题讨论】:

标签: c++ namespaces overloading name-lookup


【解决方案1】:

您的代码导致递归调用。当kthLargestAlgorithms::kthLargest 中被调用时,名称kthLargest 将在命名空间Algorithms 中找到,然后name lookup 停止,不再检查范围(例如全局命名空间)。之后,执行重载决议并失败,因为参数不匹配。

你可以改成

namespace Algorithms
{
   int kthLargest(std::vector<int> const& nums, int k)
   {
      // refer to the name in global namespace
      return ::kthLargest(nums, 0, nums.size() - 1, k);
      //     ^^
   }
}

namespace Algorithms
{
   using ::kthLargest;  // introduce names in global namespace
   int kthLargest(std::vector<int> const& nums, int k)
   {
      return kthLargest(nums, 0, nums.size() - 1, k);
   }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2010-10-20
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多