bet*_*use 4 c++ overloading namespaces name-lookup
这是不允许的吗?有人可以解释为什么吗?
namespace Algorithms
{
int kthLargest(std::vector<int> const& nums, int k);
}
Run Code Online (Sandbox Code Playgroud)
#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
Run Code Online (Sandbox Code Playgroud)
我遇到的错误是:
> /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);
Run Code Online (Sandbox Code Playgroud)
您的代码导致递归调用。当kthLargest被调用 inside 时Algorithms::kthLargest,名称kthLargest将在名称空间中找到Algorithms,然后名称查找停止,不会检查进一步的范围(例如全局名称空间)。之后,执行重载解析并失败,因为参数不匹配。
你可以把它改成
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);
// ^^
}
}
Run Code Online (Sandbox Code Playgroud)
或者
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);
}
}
Run Code Online (Sandbox Code Playgroud)