c++ - 运算符重载取模函数

标签 c++ operator-overloading

我应该重载模数函数,但我不确定该怎么做。如果您需要更多信息,请告诉我。

这是我学校的要求:

将 Point 绕原点旋转指定度数的成员函数。返回一个新点

在驱动文件里面,我的学校想要取模函数来完成这个场景:

点 pt1(-50, -50);
双角 = 45;
点 pt2 = pt1 % 角度;

这是我试过的:

Point Point::operator%( int value)
{
    (int)x%value;

    (int)y%value;

    return *this;
}

//point.h file

 class Point
 {
   public:
       // Constructors (2)
  explicit Point(double x, double y); 

  Point();

   double getX() const;

   double getY() const;

   Point operator+(const Point& other)const ;

   Point& operator+(double value);

   Point operator*(double value) ;

   Point operator%(int value);

   Point operator-(const Point& other)const ;

   Point operator-(double value);

   Point operator^(const Point& other);

   Point operator+=(double value);
   Point& operator+=(const Point& other) ;

   Point& operator++();
   Point operator++(int); 

   Point& operator--(); 
   Point operator--(int); 

   Point& operator-();

        // Overloaded operators (14 member functions)
   friend std::ostream &operator<<( std::ostream &output, const Point 
  &point );
    friend std::istream &operator>>( std::istream  &input, Point 
  &point );

    // Overloaded operators (2 friend functions)

private:
  double x; // The x-coordinate of a Point
  double y; // The y-coordinate of a Point

    // Helper functions
  double DegreesToRadians(double degrees) const;
  double RadiansToDegrees(double radians) const;
};

 // Point& Add(const Point& other); // Overloaded operators (2 non-member, non-friend functions)
    // Point& Multiply(const Point& other);
    Point operator+( double value, const Point& other );
    Point operator-( double value, const Point& other );

最佳答案

我看到的第一个错误是您没有遵守作业要求。您的作业特别要求您的类型支持此操作:

Point pt1{-50, 50};
Point pt2 = pt1 % 45.5;

这表明您的运算符必须返回一个点,并使用 double 值对其应用操作。您显然将角度存储为双倍,但收到一个 int。那是不尊重你的要求。此外,您返回一个旋转点,但不是正确的点。您正在就地进行操作,而不是在新点上进行操作。在您的运算符(operator)内部,您应该使用新位置创建一个点。像这样:

Point Point::operator%(double) const {
    return Point{..., ...};
}

那么,你的操作是错误的。您将点数据成员转换为 int 只是为了对它们进行取模。模数不做旋转。旋转通常用正弦和余弦来完成。您不能对 int 使用 C++ % 运算符进行旋转。

关于c++ - 运算符重载取模函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526633/

相关文章:

Android NDK - 在 Application.mk 中使用 APP_STL

c++ - 嵌套的 lambda 和可变关键字

c# - 有没有办法重构 C# 独有的 switch 语句?

java - Java编译器如何实现二元运算符

C++ 在结构中重载 operator()

python - 在 Python 中编写双重不等式时运算符的优先级是什么(在代码中明确说明,如何为数组覆盖?)

c++ - 在 C++ 中查找 2 个数字的比率

c++ - lambda 表达式的执行策略问题

c++ - 运算符重载的隐式交换性

c++ - 在 C++ 中绕过 operator new 的重写