class Point
{
private:
int X, Y;
public:
static const Point Origin;
static const Point OneZero;
static const Point ZeroOne;
};
我如何访问原点?
答案 0 :(得分:3)
对于静态,写:
Point::Origin
或更完整的例子:
namespace Someplace {
int fun() {
return Point::Origin.X;
}
}
虽然在课堂范围内不需要资格Point::
- 您只需撰写Origin
。
答案 1 :(得分:1)
向您的班级添加访问者(“getters”),如下所示:
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;}
};
然后您可以像这样访问Point的内容:
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();
};