其他分享
首页 > 其他分享> > c – 让课程与运算符一起工作的更简单方法?

c – 让课程与运算符一起工作的更简单方法?

作者:互联网

在这里,我有一个名为Value的类,它只能获取并设置float.

class Value
{
public:
    Value(float f)
    :f(f){};
    float get()
    {
        return f;
    }
    void set(float f)
    {
        this->f = f;
    }
private:
    float f;
};

我希望我的班级能够像以下示例一样工作.

Value value(3);
std::cout << value * 2 - 1 << std::endl; // -> 5
std::cout << value == 5 << std::endl; // -> true
value /= 2; 
std::cout << value << std::endl; // -> 2.5

我应该手动将所有操作符方法添加到我的类中吗?

或者是否有更容易的解决方案来像浮动一样对待价值?

解决方法:

以下是相关算术,相等和流运算符的惯用实现.

内联评论中的注释.

另请参阅有关允许从float进行隐式转换的后果/好处的说明.

#include <iostream>

class Value
{
public:
    // Note - this constructor is not explicit.
    // This means that in an expression we regard a float and a Value on the
    // right hand side of the expression as equivalent in meaning.
    // Note A.
    //      =
    Value(float f)
    :f(f){};

    float get() const
    {
        return f;
    }

    void set(float f)
    {
        this->f = f;
    }

    // Idiom: unary operators defined as class members
    // 
    Value& operator *= (Value const& r)
    {
        f *= r.f;
        return *this;
    }

    Value& operator -= (Value const& r)
    {
        f -= r.f;
        return *this;
    }

    Value& operator /= (Value const& r)
    {
        f /= r.f;
        return *this;
    }

private:
    float f;
};

// Idiom: binary operators written as free functions in terms of unary operators

// remember Note A? A float will convert to a Value... Note B
//                                                          =
auto operator*(Value l, Value const& r) -> Value
{
    l *= r;
    return l;
}

auto operator-(Value l, Value const& r) -> Value
{
    l -= r;
    return l;
}

auto operator<<(std::ostream& l, Value const& r) -> std::ostream&
{
    return l << r.get();
}

// Idiom: binary operators implemented as free functions in terms of public interface
auto operator==(Value const& l, Value const& r) -> bool
{
    return l.get() == r.get();
}

int main()
{
    Value value(3);
    // expressions in output streams need to be parenthesised
    // because of operator precedence
    std::cout << (value * 2 - 1) << std::endl; // -> 5
    // ^^ remember note B? value * 2 will resolve to value * Value(2) because of
    // implicit conversion (Note A)
    std::cout << (value == 5) << std::endl; // -> true
    value /= 2; 
    std::cout << value << std::endl; // -> 2.5
}

标签:c,class,operator-keyword
来源: https://codeday.me/bug/20190828/1746868.html