Why constructor is not called for given casting operator?

后端 未结 4 1344
南旧
南旧 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:06

    The Standard doesn't allow chained implicit conversion. If it was allowed, then you could have written such code:

    struct A
    {
       A(int i) //enable implicit conversion from int to A
    };  
    struct B
    {
       B(const A & a); //enable implicit conversion from A to B
    };
    struct C
    {
       C(const B & b); //enable implicit conversion from B to C
    }; 
    C c = 10; //error
    

    You cannot expect that 10 will convert to A which then will convert to B which then converts to C.


    B b = 10; //error for same reason!
    
    A a = 10;        //okay, no chained implicit conversion!
    B ba = A(10);    //okay, no chained  implicit conversion!
    C cb = B(A(10)); //okay, no chained implicit conversion!
    C ca = A(10);    //error, requires chained implicit conversion
    

    The same rule applies for implicit conversion that invokes operator T() implicitly.

    Consider this,

    struct B {};
    
    struct A 
    {
       A(int i); //enable implicit conversion from int to A
       operator B(); //enable implicit conversion from B to A
    };
    
    struct C
    {
       C(const B & b); //enable implicit conversion from B to C
    }; 
    
    C c = 10; //error
    

    You cannot expect that 10 will convert to A which then will convert to B(using operator B()) which then converts to C. S

    Such chained implicit conversions are not allowed. You've to do this:

    C cb = B(A(10);  //okay. no chained implicit conversion!
    C ca = A(10);    //error, requires chained implicit conversion
    

提交回复
热议问题