0

私はコードの一部を持っています、それはメソッド定義です

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はそれが何であるか考えていますか?

4

1 に答える 1

7

クラススコープで定義addする必要があります:Move

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

それ以外の場合は、非メンバー関数として解釈され、Moveの非パブリック メンバーにはアクセスできません。

x2 つのパラメーター コンストラクター セットとを想定すると、コードを単純化できることに注意してくださいy

Move Move::add(const Move & m) const {
    return Move(m.x + this-x, m.y + this->y);
}
于 2013-02-24T09:37:03.550 に答える