lundi 4 juillet 2022

a question about ambiguous class-type conversion in c++ [duplicate]

class Yun
{
    int q;
    friend Yun operator+(const Yun& a, const Yun& b)
    {
        Yun c = a;
        c.q += b.q;
        return c;
    }
public:
    Yun(int i) :q(i) {
    }
    operator int() const
    {
        return q;
    }
};

if i compile the follow one,compiler would tell me


ambiguous overload for ‘operator+’ (operand types are ‘Yun’ and ‘int’)

candidate: ‘operator+(int, int)’

int i=y+2;

candidate: ‘Yun operator+(const Yun&, const Yun&)’

friend Yun operator+(const Yun& a,const Yun& b)


This means that both operator+ are taken into account,right?

int main()
{
    Yun y(3);
    int i=y+2;
    return 0;
}

now i add the qualifier explicit,other unchanged

explicit operator int() const
{
   return q;
}

compile it,the complier tell me


cannot convert ‘Yun’ to ‘int’ in initialization


But what I think is that since the previous two operator+ are taken into account,and now the one of them "operator int()" qualified with qualifier explicit so that “operator+(int, int)” is impossible to be choose,why compiler don't choose to converse 2 into Yun,and perform operator(const Yun& a,const Yun& b).

Also I found,if my main function code like this--removing the "int i=",and it can work!why?

int main()
{
    Yun y(3);
    y+2;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire