开发者

What is the best practice of type conversion overloading?

开发者 https://www.devze.com 2023-04-04 02:38 出处:网络
class A { public: A ( unsigned _a ) : a (_a) { } operator unsigned& () { return a; } operator const unsigned () const
class A
{
public:
    A ( unsigned _a ) : a (_a)
    {
    }
    operator unsigned& () 
    {
        return a;
    }
    operator const unsigned () const
    {
        return a;
    }
    unsigned a; 
}; 

In the above example, I created two type conversion operators, one gives reference, one gives a copy. Both have drawbacks. Any suggestion?


Since type conversion ope开发者_StackOverflow中文版rator is allowed in C++, how can we make best use of it and where?


How about making the second one const as you're returning a copy anyway. That will remove the ambiguity:

class A
{
public:
    A ( unsigned _a ) : a (_a)
    {
    }
    operator unsigned& () 
    {
        return a;
    }
    operator unsigned () const // make this one const
    {
        return a;
    }
    unsigned a; 
}; 
0

精彩评论

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

关注公众号