我坚持与一元运算符重载问题。因此,在下面所示的代码,我基本上没有得到我的学校相匹配所需的结果。请参阅下面的信息。还有在功能上有一些限制,我不能添加任何参数,否则它给了我一个编译错误。所以,我应该怎么办呢?不要让我知道如果你需要更多的信息。谢谢!
Point& Point::operator-()
{
x = -x;
y = -y;
return *this;
}
这里的结果:
**********我的一元试**********
PT1 =(3,4)
PT2 = -pt1
PT1 =(-3,-4)
慢=(P,4)
PTA =(第4页)
PT4 = - - -pt3
PTA =(P,4)
PT4 =(邻,-4)
**********学校的一元试**********
PT1 =(3,4)
PT2 = -pt1
PT1 =(3,4)//
慢=(P,4)
PTA =(第4页)
PT4 = - - -pt3
PTA =(P 4)//
PT4 =(邻,-4)
驱动程序文件
void UnaryTest(void)
{
cout << "\n********** Unary test ********** " << endl;
Point pt1(3, 4);
cout << "pt1 = " << pt1 << endl;
Point pt2 = -pt1;
cout << "pt2 = -pt1" << endl;
cout << "pt1 = " << pt1 << endl;
cout << "pt2 = " << pt2 << endl;
cout << endl;
Point pt3(-3, 4);
cout << "pt3 = " << pt3 << endl;
Point pt4 = - - -pt3;
cout << "pt4 = - - -pt3" << endl;
cout << "pt3 = " << pt3 << endl;
cout << "pt4 = " << pt4 << endl;
}
list.h文件
class Point
{
public:
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 operator-(double value);
但是你的实现是:
Point& Point::operator-()
这可不行(注意参考和不同的参数!)。
此外,你不应该修改对象在地方这个操作符。相反,你应该有这样的:
Point operator-() const;
接着:
Point Point::operator-() const
{
return Point(-x, -y);
}