[英]Operator overload function
編譯如下所示的operator-(雙值)功能代碼時,收到一條錯誤消息。 該代碼僅用於查找點到原點的距離。 請告訴我我哪里出問題了,並告訴我如何解決。 如果您需要更多信息,請告訴我。 謝謝!
編譯錯誤消息:
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 );
Point
類的構造函數采用兩個參數x
和y
,而sqrt
的結果為單個值。 如果要兩次使用相同的值,則可以創建一個接受單個值的構造函數,或者將sqrt
的結果分配給一個變量,然后將該變量兩次傳遞給構造函數。
您需要制作一個采用double
參數的Point
構造函數。
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-您在函數中執行的Point - double
減法邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.