How to convert C++ class/struct to a primitive/different type/class/struct?

♀尐吖头ヾ 提交于 2019-12-23 00:51:24

问题


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!


回答1:


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)
{
}



回答2:


You need to provide operator int() to your class to allow the implicit conversion to int.




回答3:


You may overload a typecast:

http://www.learncpp.com/cpp-tutorial/910-overloading-typecasts/



来源:https://stackoverflow.com/questions/1699532/how-to-convert-c-class-struct-to-a-primitive-different-type-class-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!