且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

函数/方法重载C ++:数据类型混乱?

更新时间:2023-11-10 21:02:04

订单没有区别。通过分析参数的类型并将它们与参数的类型匹配来选择调用的方法。如果没有完全匹配,则选择***匹配方法。在你的情况下,它恰好是 bool 方法。

The order makes no difference. The method to call is selected by analyzing the types of arguments and matching them to the types of parameters. In case there's no exact match, the best-matching method is selected. In your case it happens to be the bool method.

您正在提供 const char [7] 的参数。根据C ++重载规则,这里***的路径是让 const char [7] 衰减到 const char * 然后使用标准转换将其转换为 bool 。转换为 std :: string 的路径被认为更糟糕,因为它涉及到 const char * std :: string 。通常,用户定义的转换对标准转换失去过载解决过程。

You are supplying an argument of type const char[7]. According to the C++ overloading rules, the best path here is to let const char[7] decay to const char * and then convert it to bool using a standard conversion. The path with converting to std::string is considered worse, since it would involve a user-defined conversion from const char * to std::string. Generally, user-defined conversions lose overload resolution process to standard conversions. This is what happens in your case as well.

如果您需要 std :: string ,为 const char * 类型提供显式重载,并通过将 std :: string std :: string $ c>的参数

If you need std::string version to be called here, provide an explicit overload for const char * type, and delegate the call to std::string version by converting the argument to std::string type explicitly

void Method(const char *paramater /* sic! */)
{
  Method(std::string(paramater));
}