gpt4 book ai didi

C++ 对构造函数的模糊调用

转载 作者:行者123 更新时间:2023-11-27 22:58:17 26 4
gpt4 key购买 nike

我有一个包含多个构造函数和重载运算符的类:

class Utf8String
{
public:

Utf8String();

explicit Utf8String( const char * sStr );

Utf8String( const char * sStrBeg, const char * sStrEnd );

Utf8String( const char * sStr, uint32_t nCpCount );

explicit Utf8String( const Utf8String & sStr );

explicit Utf8String( const Utf8String & sStr, uint32_t nStart = 0, uint32_t nCpCount = UINT32_MAX );

Utf8String( uint32_t nCpCount, uchar32_t cCodePoint );

explicit Utf8String( long int iVal );

explicit Utf8String( double fVal );

// More stuff

inline Utf8String operator + ( const char * sStr ) const
{
Utf8String sRes( *this ); // ERROR
return sRes += sStr;
}

inline operator const char * () const;

inline operator char * ();

inline operator long int () const;

inline operator double () const;
};

出于某种原因,我遇到了一个错误:

Error   3   error C2668: 'core::Utf8String::Utf8String' : ambiguous call to overloaded function c:\xxx\utf8string.h 280

我尝试在似乎有意义的地方添加明确的关键字。我还向所有构造函数添加了 explicit,只是为了看看会发生什么,但无论我做什么,我都会收到此错误并且无法弄清楚原因。

你有想法吗?谢谢。

最佳答案

这两个函数:

explicit Utf8String( const Utf8String & sStr );

explicit Utf8String( const Utf8String & sStr, uint32_t nStart = 0, uint32_t nCpCount = UINT32_MAX );

不应同时存在。他们导致了问题。

由于第二个构造函数的其余参数具有默认值,如果您只传递一个参数,它们将导致模棱两可的错误,如下所示:

 Utf8String s = get_utfString();

Utf8String s1(s); //which above constructor should be called?

一个修复方法是:删除第二个构造函数的默认值。

此外,这些构造函数是复制构造函数,因此,explicit 没有多大意义。您可以使用 explicit 来避免从一种类型 X 到另一种类型 Y隐式 版本。在这种情况下,避免从 Utf8String const&Utf8String 的隐式转换没有意义,因为这样的转换不会真正导致问题(如果是,那么问题是可能在您代码的其他部分)。

关于C++ 对构造函数的模糊调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30391653/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com