2013-02-24 47 views
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有什麼想法?

回答

7

您需要在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的非公共成員。

注意,您可以簡化代碼,假設這兩個參數的構造函數設置xy

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

+1(在等待'const'露面= P) – WhozCraig 2013-02-24 09:39:05

相關問題