算子一元重载功能
Operator unary overloading function
我遇到了一元运算符重载的问题。因此,在下面显示的代码中,我基本上没有得到与我的学校相匹配的预期结果。有关更多信息,请参见下文。函数有一些限制,我不能添加任何参数,否则会给我一个编译错误。那么我该怎么办呢?如果您需要更多信息,请告诉我。谢谢!
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);
}
相关文章:
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 你能帮我了解重载一元运算符和二进制运算符之间的区别吗?
- 算子一元重载功能
- 如何在C++中重载一元和二进制减号运算符
- 重载的"运算符+"必须是一元或二进制运算符错误
- 如何重载一元/运算符
- 运算符重载:一元运算符重载函数返回在此代码中如何工作
- 为什么我们必须从一元前缀运算符重载返回 const 引用
- C++中一元运算符重载困难
- C++中的一元运算符重载类型(新手)
- 使用 +(一元加号)解决 lambda 的函数指针和 std::function 上的不明确重载
- 为后缀重载一元运算符
- - c++中的一元操作符重载
- 除了++和——之外,是否可以重载后置一元操作符?
- 重载一元运算符 &