Why constructor is not called for given casting operator?

后端 未结 4 1339
南旧
南旧 2021-01-18 09:23
struct A {}; 
struct B
{
  B (A* pA) {}
  B& operator = (A* pA) { return *this; }
};

template
struct Wrap
{
  T *x; 
  operator T* () { return         


        
4条回答
  •  抹茶落季
    2021-01-18 10:20

    This is because C++ Standard allows only one user-defined conversion. According to §12.3/4:

    At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.

    B oB = a; // not tried: ob( a.operator T*() ), 1 conversion func+1 constructor
    oB = a;   // OK: oB.operator=( a.operator T*() ), 1 conversion func+1 operator=
    

    As a workaround you can use explicit form of calling the constructor:

    B oB( a ); // this requires only one implicit user-defined conversion
    

提交回复
热议问题