I have the following class CppProperty class that holds value:
template<typename TT>
class CppProperty
{
TT val;
public:
CppProperty(void)
{
}
CppProperty(TT aval) : val(aval)
{
}
CppProperty(const CppProperty & rhs)
{
this->val = rhs.val;
}
virtual ~CppProperty(void)
{
}
TT operator=(TT aval)
{
this->val = aval;
return this->val;
}
friend TT operator++(CppProperty & rhs);
friend TT operator--(CppProperty & rhs);
friend TT operator++(CppProperty & rhs, int);
friend TT operator--(CppProperty & rhs, int);
开发者_运维技巧 //template<typename RR>
//friend RR operator=(RR & lhs, const CppProperty & rhs);
//friend int & operator=(int & lhs, const CppProperty & rhs);
//int reinterpret_cast<int>(const CppProperty & rhs);
};
I want to do assignment like this:
CppProperty<char> myproperty(10);
myproperty++;
int count = myproperty;
How this can be done? I can't override the operator=. Any help is greatly appreciated! Thank you!
You'd need a conversion operator:
operator const TT&(void) const
{
return val;
}
operator TT&(void)
{
return val;
}
There is a brief tutorial on conversion operators here. In short, when the compiler tries to convert a type, it will first look at the right-hand side for an operator that will convert it to the desired type. What we are doing is saying "Whatever TT
is, this class can be converted to it".
If no operators are found, it looks to see if the left-hand side can be constructed from the right-hand side, and so on. (Until, if it cannot find a conversion, it emits an error.)
You can remove your explicitly defined default constructor if you declare your other constructor like this:
// If not specified, construct with default-constructed type.
CppProperty(TT aval = TT()) : val(aval)
{
}
You need to provide operator int()
to your class to allow the implicit conversion to int.
You may overload a typecast:
http://www.learncpp.com/cpp-tutorial/910-overloading-typecasts/
精彩评论