问题描述
我正在 MS Visual C++ 6.0 下编写程序(是的,我知道它很古老,不,我无能为力升级).我看到了一些我认为非常奇怪的行为.我有一个包含两个构造函数的类,定义如下:
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("blah")
,它调用第一个构造函数.正如您所看到的,我向它添加了 explicit
关键字,希望它不会这样做……没有骰子.它似乎更喜欢从 const char *
到 bool
的转换,而不是到 RWCString
的转换,后者有一个接受 const 字符 *
.它为什么这样做?我认为,如果有两种可能的选择,它会说这是模棱两可的.我能做些什么来防止它这样做?如果可能的话,我想避免将 strPath
参数显式转换为 RWCString
,因为它将与文字一起使用很多,而且很多额外的输入(加上一个非常容易犯的错误).
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.
无法控制首选的转换顺序,但您可以添加第二个采用 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;
};
这篇关于调用函数时首选错误的参数转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!