注册 登录
编程论坛 C++教室

‘++’符号重载出现错误 error C2676

家力掠 发布于 2016-04-17 16:37, 6663 次点击
程序代码:
    -----point.h
class Point
{
public:
    Point();
    Point(float x, float y);
    ~Point();
        Point operator ++();
    Point operator --();
private:
    float x, y;
}

      -----point.cpp
Point Point::operator ++()
{
   
    this->x = this->x + 1;
    this->y = this->y + 1;
    return *this;
}

Point Point::operator --()
{
    this->x = this->x - 1;
    this->y = this->y - 1;
    return *this;
}

            ------main.cpp
        Point r5. r6;
        r5 = p1++;
    r6 = p1--;



VS2015 错误:
1>c:\users\busters\documents\visual studio 2015\projects\c++作业\overload\overload\overload.cpp(14): error C2676: 二进制“++”:“Point”不定义该运算符或到预定义运算符可接收的类型的转换

1>c:\users\busters\documents\visual studio 2015\projects\c++作业\overload\overload\overload.cpp(15): error C2676: 二进制“--”:“Point”不定义该运算符或到预定义运算符可接收的类型的转换
5 回复
#2
家力掠2016-04-17 18:53
没人吗
#3
rjsp2016-04-18 12:44
贴代码,代码应当完整且不含无关的垃圾,否则别人不愿意浪费时间补完你的代码,并且和你一一确认某某处是不是输入错误(比如,class Point定义完毕后是不是忘了分号,比如r5. r6中是不是逗号打错成分号了,main中p1是什么,等等)

程序代码:
class Point
{
public:
    Point();
    Point& operator++();
    Point& operator--();
private:
    double x, y;
};

Point::Point() : x(0), y(0)
{
}

Point& Point::operator++()
{
    x = x + 1;
    y = y + 1;
    return *this;
}

Point& Point::operator--()
{
    x = x - 1;
    y = y - 1;
    return *this;
}

#include <iostream>

int main( void )
{
    Point a;
    ++a;

    Point b;
    --b;

    return 0;
}

#4
家力掠2016-04-18 13:17
回复 3楼 rjsp
非常感谢你的帮助。

为什么使用  ++a 不会报错  而使用a++会报错?

#5
rjsp2016-04-18 22:18
因为你重载的是++a,不是a++
#6
仰望星空的2016-04-20 10:09
运算符重载,相当于重新写了函数,比如operator ++()之后,你在计算++a时候,此时调用的是operator++(a),那个a可理解为函数的参数,
如果是a++,相当于重载函数没有相应的参数去传递给operator++()了,所以会出错。
重载a++,可以是Point Point::operator ++(int)
1