简体   繁体   中英

How can i access a static class member?

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

How can i acces the point Origin?

for a static, write:

Point::Origin

or a more complete example:

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

although the qualification Point:: is not necessary when inside the class' scope -- you can simply write Origin .

Add accessors ("getters") to your class as follows:

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;}
};

Then you can access the contents of a Point like this:

int originX = Origin.getX();

Or like this:

Point myPoint;
int pointX = myPoint.getX();

Also, it's confusing that there are static instances of the class Point within the class Point. The following might be more what you're trying to do:

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();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM