开发者

C++ auto conversions

For two unrelated classes "class A" and "class B" and a function

B convert(const A&);

Is t开发者_高级运维here a way to tell C++ to automatically, for any function that takes "class B" as argument, to auto convert a "class A".

Thanks!


What you would normally do in this case is give B a constructor that takes an A:

class B
{
public:
    B(const A&);
};

And do the conversion there. The compiler will say "How can I make A a B? Oh, I see B can be constructed from an A".

Another method is to use a conversion operator:

class A
{
public:
    operator B(void) const; 
}

And the compiler will say "How can I make A a B? Oh, I see A can be converted to B".

Keep in mind these are very easy to abuse. Make sure it really makes sense for these two types to implicitly convert to each other.


You can supply a cast operator, or a one-parameter constructor.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜