重载类实例变量

Overload Class Instance Variable

本文关键字:变量 实例 重载      更新时间:2023-10-16

我一直在寻找这个,但没有任何运气。可能是我搜索了错误的单词,或者这是一个不寻常的请求(或者根本不可行)。

无论如何,我的问题:我希望能够使用类的实例......好吧,这里有一个非常简单的例子:

class attribute
{
    float value;
    float min;
    float max;
}
attribute attr1;
attr1.value = 5.0f;

现在,基本上,我想使用 attr1,就好像我在调用

attr1.value

所以当我说,

std::cout << attr1 << std::endl;

它将打印 5.0(或仅 5)。

谢谢!

你需要实现

std::ostream& operator<<(std::ostream& os, attribute const& att)
{
    os << att.value;
    return os; // this is how you "chain" `<<`
}

要么允许att.value通过publicfriend船,要么编写一个函数。

另一种选择是构建一个铸造运算符来float

class attribute
{
    public:
    operator float() const
    {
        return value;
    }
    private:
    /*the rest of your class here*/

但这可能会带来意想不到的歧义。

最后,如果您希望attribute的行为类似于数字类型,则可以根据需要重载更多运算符。例如,要重载+=,您可以编写

template<typename Y>
attribute& operator+=(const Y& p)
{
    value += p;
    return *this;
}