1
class Point
{
private:
int X, Y;
public:
static const Point Origin;
static const Point OneZero;
static const Point ZeroOne;
};
我如何訪問點起源?如何訪問靜態類成員?
class Point
{
private:
int X, Y;
public:
static const Point Origin;
static const Point OneZero;
static const Point ZeroOne;
};
我如何訪問點起源?如何訪問靜態類成員?
爲靜態,寫:
Point::Origin
或更完整的示例:
namespace Someplace {
int fun() {
return Point::Origin.X;
}
}
雖然資格Point::
是沒有必要的時候類範圍內 - 你可以簡單地寫Origin
。
添加存取( 「干將」)將類,如下所示:
class Point
{
private:
int X, Y;
public:
static const Point Origin;
static const Point OneZero;
static const Point ZeroOne;
int getX() {return X;}
int getY() {return Y;}
};
然後你就可以訪問點的內容是這樣的:
int originX = Origin.getX();
或者這樣:
Point myPoint;
int pointX = myPoint.getX();
另外,令人困惑的是Point類中存在類Point的靜態實例。以下可能更多你想要做什麼:
class Point
{
public:
// Added a constructor that takes two arguments
Point(int pointX, int pointY) {X = pointX; Y = pointY;}
int getX() {return X;}
int getY() {return Y;}
private:
int X, Y;
};
int main()
{
const Point Origin(0,0);
const Point OneZero(1,0);
const Point ZeroOne(0,1);
int originX = Origin.getX();
};
添加getters訪問私人會員。 'getX()'和'int getY()' – andre 2013-02-28 16:16:41
ADD類的方法如:'getX(){return this-> x}' – 2013-02-28 16:16:46
「access」是什麼意思?我也希望我可以減少評論。 – 2013-02-28 16:17:14