操作员过载功能 [英] Operator overload function

查看:52
本文介绍了操作员过载功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I received an error message when compiling the operator-(double value) function code shown below. The code is merely to find The distance of a point from the origin. Please enlighten me on where i've gone wrong and show me how you resolve it. Let me know if you require more info. Thanks!

编译错误消息:

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

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

The code is used to achieve this in the driver file:

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

推荐答案

您的Point类构造函数采用两个参数xy,而sqrt的结果是单个值.如果要两次使用相同的值,则可以创建一个接受单个值的构造函数,或者将sqrt的结果分配给变量,然后将该变量两次传递给构造函数.

Your Point class constructor takes two parameters, x, and y, whereas the result of sqrt is a single value. If you want to use the same value twice, then either make a constructor which accepts a single value, or assign the result of sqrt to a variable, and then pass that variable into the constructor twice.

这篇关于操作员过载功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆