让类与运算符一起工作更简单的方法

Easier way to make class to work with operators?

本文关键字:更简单 方法 工作 一起 运算符      更新时间:2023-10-16

这里,我有一个名为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一样治疗Value吗?

您可以使用float类型的转换运算符来代替get()

operator float() const { return f; }

如果还希望启用更改值的操作(如/=),可以使用类似的返回引用的非常数运算符,也可以手动添加这些运算符。

但是,如果您想要一个行为与float完全相同的类,那么最好使用float,而不是使用Value类。

这里是相关算术、等式和流运算符的惯用实现。

内联注释中的注释。

另请参阅关于允许从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
}

我实现了/===运算符:

您可以使用此页面了解更多。。。https://www.tutorialspoint.com/cplusplus/cpp_overloading.htm

class Value
{
public:
Value(float f) : f(f) {};
operator float() const
{
return f;
}
void set(float f)
{
this->f = f;
}
Value &operator /=(float num)           // e.g. value /= 2;
{
this->f = f / num;
}
bool operator==(const float& a) const    // e.g. std::cout << value == 5 << std::endl; // -> true
{
if(this->f == a) return true;
return false;
}
private:
float f;
};

main:

int main()
{
Value value(10);
value /= 5;
cout << value << endl;
cout << (value == 5) << endl;
return 0;
}