1
class Point
{
  private:
    int X, Y;  
  public:
    static const Point Origin;
    static const Point OneZero;
    static const Point ZeroOne;
};

我怎样才能访问点原点?

4

2 回答 2

3

对于静态,写:

Point::Origin

或更完整的示例:

namespace Someplace {
int fun() {
  return Point::Origin.X;
}
}

尽管在Point::课程范围内不需要资格 - 你可以简单地写Origin.

于 2013-02-28T16:18:08.073 回答
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();
};
于 2013-02-28T16:20:16.203 回答