操作员过载功能

时间:2019-02-05 09:27:55

标签: c++ operator-overloading

编译如下所示的操作符(双值)功能代码时收到错误消息。该代码仅用于查找点到原点的距离。请告诉我我哪里出问题了,并告诉我如何解决。如果您需要更多信息,请告诉我。谢谢!

编译错误消息:

Point.cpp: In member function ‘CS170::Point CS170::Point::operator- 
(double)’:

Point.cpp:187:49: error: no matching function for call to 

‘CS170::Point::Point(double)’

 return Point(sqrt(((x * value) + (y * value))));
                                               ^

该代码用于在驱动程序文件中实现此目的:

pt3 = pt1 - 2;

  Point Point::operator-(double value)
{

    Point temp;
    temp=sqrt(((x * value) + (y * value)));
    return temp ;

}

// list.h文件

 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%(double angle);


   double 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 );

2 个答案:

答案 0 :(得分:1)

您的std::vector<char>类构造函数采用两个参数using Number = int; enum class Operator { Plus, Minus, Div, Mul }; using Token = std::variant<Number, Operator> using Sequence = std::vector<Token>; Point,而x的结果是单个值。如果要两次使用相同的值,则可以创建一个接受单个值的构造函数,或者将y的结果分配给变量,然后将该变量两次传递给构造函数。

答案 1 :(得分:0)

您需要制作一个带有Point参数的double构造函数。

Point (double d){
   //whatever logic of point construction.
};

解决行中的错误。

temp=sqrt(((x * value) + (y * value)));

但是最终会构建一个像这样的点。

Point P = 5;

在其他地方,您可能不希望发生这种情况。

在您的鞋子中,我将其设为显式构造函数。

explicit Point(double d){
   //whatever logic of point construction.
};

那样,您最终将需要初始化从doublePoint

Point P1 = (Point)5;
Point P2 = (Point)sqrt(((x * value) + (y * value)));

最后,我将讨论您在函数中执行的Point - double减法逻辑。