运算符重载函数

问题描述 投票:0回答:2

编译下面所示的操作符 - (双精度值)函数代码时,我收到错误讯息。该代码只是为了找到原点的点的距离。请赐教在哪里我已经错了,让我看看你怎么解决它。让我知道如果你需要更多的信息。谢谢!

编译错误信息:

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 );
c++ operator-overloading
2个回答
1
投票

Point类的构造函数有两个参数,xy,而sqrt的结果是一个值。如果你想使用相同的值的两倍,那么无论做它接受单个值的构造函数或sqrt的结果分配给一个变量,然后传递变量到构造函数的两倍。


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.
};

这样,你最终会初始化你的观点这样需要从double明确铸造Point

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

最后我会争论,你在你的函数是做减法Point - double逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.