开发者

Why typecasting operator doesn't work with inherited class?

开发者 https://www.devze.com 2023-03-23 00:07 出处:网络
I ha开发者_JAVA技巧ve two classes: struct B {}; struct D { operator B& (); }; When I do; b = d; // B b; ... D d;

I ha开发者_JAVA技巧ve two classes:

struct B {};
struct D {
  operator B& ();
};

When I do;

b = d; // B b; ... D d;

Result is as per expectation where D::operator B&() is invoked (Demo).

If the D is changed to,

struct D : B {
  operator B& ();
};

then D::operator B&() is not invoked (Demo). Is B::B(const B&) is finding a better candidate in D then D::operator B&() ?


If D derives from B, there is an implicit automatic conversion from D to B. This has higher precedence than a user-defined conversion operator.

0

精彩评论

暂无评论...
验证码 换一张
取 消