[英]cannot access private member declared in class
我有一段代碼,它是方法定義
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.