Sho*_*hoe -3 c++ operator-overloading
是否可以创建一个类型(比如说degrees)并为它定义特定的运算符?如:=, +, *, -, /, +=, *=, -=, /=.
我想知道这是因为我需要为我的一个程序使用度数而我不想使用一个float对象,因为使用它degrees a; a.value = 120; a.value = b.value + a.value;是一个简单的冗余degrees a = 120; a = b+a;.
现在我为什么不使用:
typedef float degrees;
Run Code Online (Sandbox Code Playgroud)
?好吧,因为我还需要一件事.当我写作
degrees a;
a = 120;
a += 300;
Run Code Online (Sandbox Code Playgroud)
a应该等于60(420-360),因为我真的不需要a = 6150什么时候能有a = 30相同的效果.所以我会重载这些运算符以保持0到360之间的值.
可能吗?如果是这样,怎么样?
您的问题的解决方案不需要Boost或任何其他库.你可以通过使用C++类来实现你想要的,并且重载你想要的数学运算符(+, - ,*,/等)和你想要的赋值运算符(=,+ =, - =等)和比较你想要的运营商(<,>,<=,> =等)......或者你想要的任何运营商!
例如:
#include <cmath>
class Degrees {
public:
// *** constructor/other methods here ***
Degrees& operator=(float rhs) {
value = rhs;
normalize();
return *this;
}
Degrees& operator+=(const Degrees &rhs) {
value += rhs.value;
normalize();
return *this;
}
Degrees operator+(const Degrees &rhs) {
return Degrees(value + rhs.value);
}
private:
float value;
void normalize() {
value = std::fmod(value, 360);
}
};
Run Code Online (Sandbox Code Playgroud)
然后你可以做这样的事情:
Degrees a, b; // suppose constructor initializes value = 0 in all of them
a = 10;
b = 20;
a += b; // now, a = 30.
Degrees c = a + b; // now, c = 50.
Run Code Online (Sandbox Code Playgroud)
我已经给你一个重载赋值和加号运算符的例子,但你可以尝试任何其他类型的相同的东西,它应该工作.
这是一个起点:
class Degrees {
public:
explicit Degrees(float value) : value(normalized(value)) { }
Degrees &operator+=(Degrees that)
{
value += that.value;
return *this;
}
private:
float value;
};
inline Degrees operator+(Degrees a,Degrees b)
{
a += b;
return a;
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
{
Degrees a(120);
Degrees b(300);
Degrees c = a+b;
}
Run Code Online (Sandbox Code Playgroud)