Visual Studio 无法解决类和命名空间中重载的明确函数
Visual studio unable to resolve overloaded unambiguous function in class and namespace
>请参阅下面的代码
#include <iostream>
#include <string>
namespace stringhelper
{
std::string to_string(int n) { return "0"; } // ignore wrong implementation. simplified for example purpose
}
using stringhelper::to_string;
class TestClass
{
public:
std::string to_string() const { return "TestClass:" + to_string(m_value); }
private:
int m_value;
};
int main()
{
TestClass tc;
std::cout << tc.to_string();
}
如果TestClass没有实现函数to_string()
,在TestClass
内,它能够解析to_string(m_value)
stringhelper::to_string(int)
。但是,当 TestClass 实现函数 to_string(( 时,编译器无法将to_string(int)
解析为stringhelper::to_string
。 相反,它坚持/解析函数以TestClass::to_string
并给出一个错误,该函数TestClass::to_string
不接受 1 个参数。
为什么会这样?
环境:
Visual Studio 2008 Professional Edition 9.0.21022.8 RTM
配置:Win32
视窗 8
此行为不限于 Visual Studio 2008。如果在现代 Clang 实现中进行测试,您将看到相同的行为。如您所知,派生类中的函数不重写基类中的函数,但具有相同名称的函数将隐藏基类中同名的其他函数。
这里的"问题"是,通过使用using
语句,您将一个名为to_string
的函数引入到一个作用域中,当从类内部查看它时,该作用域本质上是与上述示例中发生的情况完全相同的受害者。
如果标准让你用this->foo()
调用成员函数,这可能不是问题。但是,由于类中的函数调用被假定为类的一部分,并且只有在其他作用域中找不到时才
会出现此问题。由于您的类中有一个实现,因此它具有优先级并将使用。由于您想要一个将int
作为参数的版本,因此将查找成员函数的重载版本,并且由于它不存在,因此会出现您看到的错误。
这就是为什么using namespace
经常会引入可能难以理解的错误的部分原因。如果要确保在具有相同名称的函数的类中使用stringhelper::to_string
实现,则必须显式。
例如,即使您保留using
语句,这也将正常工作。
#include <iostream>
#include <string>
namespace stringhelper
{
std::string to_string(int n) { return "0"; } // ignore wrong implementation. simplified for example purpose
}
using stringhelper::to_string;
class TestClass
{
public:
std::string to_string() const { return "TestClass:" + stringhelper::to_string(m_value); }
private:
int m_value;
};
int main()
{
TestClass tc;
std::cout << tc.to_string();
}
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 可以打印矢量和矢量中的矢量的非重载C++函数
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 使用模板重载函数
- C++线程中,没有重载函数接受 X 参数
- std::vector 没有重载函数的实例与参数列表匹配
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 错误:无法解析对重载函数的引用;你的意思是调用它吗?
- 对重载函数find_first_not_of的不明确调用
- 如何从重载解析中删除重载函数?
- CUDA:重载函数"isnan"的多个实例
- C++派生类重载函数(带有 std::function 参数)不可见
- 避免在人为的重载函数调用中拼写出类型
- C++:如何为多个重载函数保留通用代码路径?
- 什么时候可以使用常量装饰调用我的重载函数?
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- std::调用,未找到匹配的重载函数
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 为什么使用不匹配的参数调用重载函数仍然有效
- 如何通过签名作为模板参数来解决重载函数?