c++ - 运算符一元重载函数
问题描述
我被一元运算符重载的问题困住了。所以在下面显示的代码中,我基本上没有得到与我学校匹配的预期结果。有关更多信息,请参见下文。函数有一些限制,我不能添加任何参数,否则它会给我一个编译错误。那么我该怎么办呢?如果您需要更多信息,请告诉我。谢谢!
Point& Point::operator-()
{
x = -x;
y = -y;
return *this;
}
结果如下:
**********我的一元测试**********
pt1 = (3,4)
pt2 = -pt1
pt1 = (-3,-4)
pt2 = (-3,-4)
pt3 = (-3,4)
pt4 = - - -pt3
pt3 = (3,-4)
pt4 = (3,-4)
**********学校的一元测试**********
pt1 = (3, 4)
pt2 = -pt1
pt1 = (3, 4)//
pt2 = (-3, -4)
pt3 = (-3, 4)
pt4 = - - -pt3
pt3 = (-3, 4)//
pt4 = (3, -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;
}
列表.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);
}
推荐阅读
- r - stat_fit_glance 和广义加性模型 (GAM) 错误
- r - 在闪亮的应用程序中使用会话参数
- linux - 如何在 bash/ksh shell 中使用 find 遍历文件
- python - 我已经安装了 python-dotenv 但 python 找不到它
- python-3.x - 理解为什么我们需要 Wheel Python 包而不是仅仅使用 sdist
- java - 如何在主要活动中使用应用程序更新管理器
- python - python - 如何从包含数字和单词的原始列表中创建一个仅包含数字和单词/短语的新列表?
- python - numpy.unique 有 freezesets 的问题
- xcode - 如何解决“开发人员工具访问需要控制另一个进程才能继续进行调试。” 在 Xcode 中?
- python - azure vm 上的 Python 套接字服务器