1
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) {
    }
    explicit operator int()
    {
        return q;
    }
};
int main()
{
    Yun y(3);
    int w = y + 2;
    return 0;
}

i make add the explicit to the operator int(),it will not be perform,why does compiler no choose the other way--performing Yun(int) to transform the second object--2.

And if i remove w value.

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

it can work,why?

air
  • 199
  • 1
  • 7
  • 1
    Because you've not defined any `Yun operator+(Yun const&, Yun const&)`. – paolo Jul 04 '22 at 08:18
  • i have edited,but it still can't work. – air Jul 04 '22 at 08:23
  • @paolo........... – air Jul 04 '22 at 08:23
  • Now the compiler will complain because you have marked the conversion from `Yun` to `int` as `explicit`. If you want the result as an `int`, do a `static_cast`. Otherwise, declare `w` as `Yun`. – paolo Jul 04 '22 at 08:25
  • You add `explicit` to tell the compiler to do conversions not implicitly, but only if you explicitly ask for it. The reason to use that is to add a conversion possibility but to prevent you from accidentally using that conversion in code. – t.niese Jul 04 '22 at 08:30
  • The additional question in your edit has already been answered. `int w = ...;` does not consider `explicit` conversion operators to convert `...` to `int`. In `y+2;` there is no assignment that needs conversion. The error is not complaining about the `+` operation, it is complaining about the `int w = ` initialization. – user17732522 Jul 05 '22 at 01:29

1 Answers1

3

The user defined conversion

explicit operator int()

is marked explicit but

int w = y + 2;

requires an implicit conversion.

Just make the conversion explicit:

int w{y + 2};

Unrelated: Since the conversion doesn't change the Yun object, make it const-qualified:

explicit operator int() const
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • I prefer it the other way. I would make all functions explicit and explicitlly call them: `int w = static_cast(y + Yun(2));` – jabaa Jul 04 '22 at 08:56
  • 1
    @jabaa Yes, that's often recommended but not the case here. If one makes the constructor `explicit` and want the objects to be easily usable in these situations without casts, adding operators `Yun& operator+(const Yun&, int)` and `Yun& operator+(int, const Yun&)` would be preferable. – Ted Lyngmo Jul 04 '22 at 09:09
  • 1
    I have not thought about that at all. You're right. That's even better. – jabaa Jul 04 '22 at 09:49
  • @jabaa It doesn't exclude your suggestion though. One often combines them. – Ted Lyngmo Jul 04 '22 at 09:50