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;
};
精彩评论