定义新类型并重载其运算符

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之间的值.

可能吗?如果是这样,怎么样?

Ash*_*gar 6

您的问题的解决方案不需要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)

我已经给你一个重载赋值和加号运算符的例子,但你可以尝试任何其他类型的相同的东西,它应该工作.

  • 不推荐使用fmodf,你应该使用std :: fmod. (3认同)
  • 这里不需要赋值运算符.`Degree`参数应该已经符合班级的合同. (3认同)
  • 这可能是一个noob问题,但不是'this`指针?你为什么用这个.*`? (2认同)
  • 在我看来,其中一些比必要复杂一些.例如,有没有理由`operator +`不能只是`return Degrees(value + rhs.value);`? (2认同)

Vau*_*ato 5

这是一个起点:

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)

  • @Jeffrey,如果你因为这个对象访问另一个对象的`value`而感到困惑,那么它就是一个类级别,而不是一个对象级别.它们都属于同一个类,因此它们都可以访问彼此的私有成员. (3认同)
  • @Jeffrey:不,会员功能可以访问私人会员. (2认同)