开发者

What is the best practice of type conversion overloading?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜