C++ 无法访问类中声明的私有成员

C++ 无法访问类中声明的私有成员,c++,visual-studio-2010,class,private,C++,Visual Studio 2010,Class,Private,我有一段代码,它是方法定义 Move add(const Move & m) { Move temp; temp.x+= (m.x +this-x); temp.y+= (m.y + this->y); return temp; } 这是类声明 class Move { private: double x; double y; public: Move(double a=0,double b=0); void sho

我有一段代码,它是方法定义

Move add(const Move & m) {
    Move temp;
    temp.x+= (m.x +this-x);
    temp.y+= (m.y + this->y);
    return temp;
}
这是类声明

class Move
{
private:
    double x;
    double y;
public:
    Move(double a=0,double b=0);
    void showMove() const;
    Move add(const Move & m) const;
    void reset(double a=0,double b=0);
};
上面说

1>c:\users\filip\dysk google\c++\consoleapplication9\move.cpp(18): error C2248: 'Move::x' : cannot access private member declared in class 'Move'
1>          c:\users\filip\dysk google\c++\consoleapplication9\move.h(7) : see declaration of 'Move::x'
1>          c:\users\filip\dysk google\c++\consoleapplication9\move.h(5) : see declaration of 'Move'
1>          c:\users\filip\dysk google\c++\consoleapplication9\move.h(7) : see declaration of 'Move::x'
1>          c:\users\filip\dysk google\c++\consoleapplication9\move.h(5) : see declaration of 'Move'
1>c:\users\filip\dysk google\c++\consoleapplication9\move.cpp(18): error C2355: 'this' : can only be referenced inside non-static member functions
1>c:\users\filip\dysk google\c++\consoleapplication9\move.cpp(18): error C2227: left of '->x' must point to class/struct/union/generic type

Move::y也是如此。Any1知道这是什么?

您需要在
Move
类范围中定义
add

Move Move::add(const Move & m) const {
    Move temp;
    temp.x+= (m.x +this-x);
    temp.y+= (m.y + this->y);
    return temp;
}
否则,它将被解释为非成员函数,无法访问
Move
的非公共成员

注意,您可以简化代码,假设两个参数构造函数集
x
y

Move Move::add(const Move & m) const {
    return Move(m.x + this-x, m.y + this->y);
}