函数/方法重载C ++:数据类型混乱? [英] Function/Method Overloading C++: Data type confusion?

查看:176
本文介绍了函数/方法重载C ++:数据类型混乱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中重载方法有些麻烦。
作为一个问题的例子,我有一个类有一些方法被重载,每个方法有一个参数有不同的数据类型。
我的问题:在这些方法应该出现在类中有一个特定的顺序,以确保正确的方法被调用取决于其参数数据类型?

I'm having some trouble overloading methods in C++. As an example of the problem, I have a class with a number of methods being overloaded, and each method having one parameter with a different data type. My question: is there a particular order in the class these methods should appear in, to make sure the correct method is called depending on its parameters data type?

class SomeClass{
    public:
    ...
    void Method(bool paramater);
    void Method(std::string paramater);
    void Method(uint64_t paramater);
    void Method(int64_t paramater);
    void Method(uint8_t paramater);
    void Method(int8_t paramater);
    void Method(float paramater);
    void Method(double paramater);
    void Method(ClassXYZ paramater);
}



我注意到有问题,因为运行时:

I noticed there was problem because when running:

Method("string");

正在呼叫:

Method(bool paramater);


推荐答案

订单没有区别。通过分析参数的类型并将它们与参数的类型匹配来选择调用的方法。如果没有完全匹配,则选择最佳匹配方法。在你的情况下,它恰好是 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 的参数

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));
}

这篇关于函数/方法重载C ++:数据类型混乱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆