如何将C ++类/结构转换为原始/不同类型/类/结构? [英] How to convert C++ class/struct to a primitive/different type/class/struct?

查看:130
本文介绍了如何将C ++类/结构转换为原始/不同类型/类/结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类CppProperty类保存值:

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

我想这样做:

CppProperty<char> myproperty(10);
myproperty++;
int count = myproperty;

如何做到这一点?我不能覆盖operator =。任何帮助,非常感谢!谢谢!

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;
}

有一个关于转换运算符的简短教程此处。简而言之,当编译器尝试转换类型时,它将首先查看右侧的一个操作符,它将它转换为所需的类型。我们所做的是说 TT 是,这个类可以转换为它。

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

这篇关于如何将C ++类/结构转换为原始/不同类型/类/结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆