因此,显然,运算符重载是C ++的一大功能。
但是说我想获得一个类的成员,只需使用变量名键入即可。
像这样:
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
}
那可能吗?有没有一种方法可以工作,并通过使用变量名称来获取成员“值”?
谢谢!
最佳答案
是的,你可以这么做。您可以通过提供转换运算符作为成员函数来实现。
operator short () const
{
return value;
}