简体   繁体   English

C ++中的隐式转换

[英]Implicit conversions in C++

Given the following code, why doesn't the compiler resolve the implicit conversion when constructing Bar ? 给定以下代码,为什么编译器在构造Bar时不解析隐式转换? That is, construct Foo just like a was constructed which is (should) then be used to construct Bar ? 也就是说,建设Foo就像a构建是(应该)被用来构建Bar

#include <string>

class ImplicitlyConvertToChar
{
public:
  ImplicitlyConvertToChar(const char* a_char)
    : m_string(a_char)
  { }

  ImplicitlyConvertToChar(const char* a_char, size_t a_end)
    : m_string(a_char)
  {
  }

  template <typename T_String>
  ImplicitlyConvertToChar(T_String const& a_string)
    : m_string(a_string.begin())
  {
  }

  operator char const * () const
  { return m_string; }

  const char* m_string;
};

class Foo
{
public:

  Foo(const ImplicitlyConvertToChar& a_charLike)
    : m_string(a_charLike)
  { }

  const char* m_string;
};

class Bar
{
public:
  Bar(const Foo& a_foo)
    : m_foo(a_foo)
  { }

  Foo m_foo;
};

int main()
{
  Foo a("this works");
  Bar b("Why doesn't this?");
}

You are not allowed more than one user defined implicit conversion. 您不允许多个用户定义的隐式转换。 The Foo example involves one, the Bar example involves two. Foo示例涉及一个, Bar示例涉及两个。

The compiler is only allowed to make a single implicit user-defined conversion. 只允许编译器进行单个隐式的用户定义转换。

See http://en.cppreference.com/w/cpp/language/implicit_cast http://en.cppreference.com/w/cpp/language/implicit_cast

A user-defined conversion consists of: 
    zero or one non-explicit single-argument constructor or non-explicit 
    conversion function calls

Constructing Bar that way would require two. 以这种方式构建Bar需要两个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM