调用函数时,错误的参数转换preferred [英] wrong argument conversion preferred when calling function

查看:99
本文介绍了调用函数时,错误的参数转换preferred的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的Visual C ++ 6.0 MS下一个程序(是的,我知道这是古老的,没有什么我可以做的升级)。我看到一些行为,我认为这是很奇怪的。我有这样定义两个构造函数的类:

I'm writing a program under MS Visual C++ 6.0 (yes, I know it's ancient, no there's nothing I can do to upgrade). I'm seeing some behavior that I think is really weird. I have a class with two constructors defined like this:

class MyClass
{
public:
    explicit MyClass(bool bAbsolute = true, bool bLocation = false) : m_bAbsolute(bAbsolute), m_bLocation(bLocation) { ; }
    MyClass(const RWCString& strPath, bool bLocation = false);

private:
    bool m_bAbsolute;
    bool m_bLocation;
};

当我实例化这个类的一个实例与此语法: MyClass的(嗒嗒),它调用第一个构造函数。正如你所看到的,我加了明确关键字它的希望,它不会做...没有骰子。这样看来,以preFER转换从为const char * 布尔在转换为 RW​​CString ,其中有一个拷贝构造函数,它接受一个为const char * 。它为什么要这样做呢?我会认为像这样给出了两个可能的选择,它会说这是不明确的。我能做些什么,以prevent它这样做呢?如果可能的话,我想避免必须显式转换 strPath的参数的 RW​​CString ,因为它是将与文字中使用了很多,这是一个很多额外的打字(加上一个非常容易犯的错误)。

When I instantiate an instance of this class with this syntax: MyClass("blah"), it calls the first constructor. As you can see, I added the explicit keyword to it in the hopes that it wouldn't do that... no dice. It would appear to prefer the conversion from const char * to bool over the conversion to RWCString, which has a copy constructor which takes a const char *. Why does it do this? I would assume that given two possible choices like this, it would say it's ambiguous. What can I do to prevent it from doing this? If at all possible, I'd like to avoid having to explicitly cast the strPath argument to an RWCString, as it's going to be used with literals a lot and that's a lot of extra typing (plus a really easy mistake to make).

推荐答案

显式的构造不是隐式转换的一部分,只是收件人将没有任何帮助。

Explicit will not help here as the constructor is not a part of the implicit conversion, just the recipient.

有没有办法来控制转换的preferred顺序,但你可以添加了一个const char *第二构造函数。例如:

There's no way to control the preferred order of conversions, but you could add a second constructor that took a const char*. E.g:

class MyClass
{
public:
    MyClass(bool bAbsolute = true, bool bLocation = false);
    MyClass(const RWCString& strPath, bool bLocation = false);
    MyClass(const char* strPath, bool bLocation = false);

private:
    bool m_bAbsolute;
    bool m_bLocation;
};

这篇关于调用函数时,错误的参数转换preferred的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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