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

标签 c++ constructor operator-overloading implicit-conversion explicit

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

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/

相关文章:

c++ - 如何在 Cocos2dx-v3 C++ 中将 Map<K, V> 与 string 和 int 一起使用?

c++ - 关于转换运算符和operator()

c++ - VS 2013 无法根据模板参数专门化具有通用引用和返回类型的函数模板

c++ - 为什么抛出这个 bad_alloc 异常?

c# - 抽象类、构造函数和 Co

go - 包含嵌入的结构 slice 的结构

c++ - 运算符重载、奇数段错误、类、C++

c++ - 如何找到重载运算符的定义?

c++ - 此函数如何通过 NOT 和 AND 运算计算 float 的绝对值?

c++ - 类型名称后的括号是否与 new 有所不同?