简体   繁体   English

为此是否存在运算符?

[英]Does an operator exist for this?

So, operators overloading is a great feature of C++, obviously. 因此,显然,运算符重载是C ++的一大功能。

But say I wanted to get a member of a class just type using the name of the variable. 但是说我想获得一个类的成员,只需使用变量名键入即可。

So like: 像这样:

class ShortProperty
{
public:
    ShortProperty(short value)
    {
        this->value = value;
    }
public:
    short operator=(short value)
    {
        this->value = value;
        return value;
    }
private:
    short value;
}

void foo()
{
    ShortProperty myproperty(2);

    // Now I can easily do...
    mtproperty = 3;

    // But say I wanted to do...
    short val = myproperty; // THIS LINE
}

Is that possible? 那可能吗? Is there a way that will work and by using the variable name, get the member "value"? 有没有一种方法可以工作,并通过使用变量名称来获取成员“值”?

Thanks! 谢谢!

Yes, you can do that. 是的,你可以这么做。 You do that by providing a conversion operator as a member function. 您可以通过提供转换运算符作为成员函数来实现。

operator short () const
{
   return value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM