0

我有一个程序可以在整个程序中创建随机数量的点。在它运行时,我还想为每个点创建一个对象并将其存储在一个向量中。我创建了一个具有各种属性的 Point 类,但我不知道如何实现上述内容。在查看处理类似但不相同的问题的其他问题时,使用了指针,但同样,我不知道如何实现它们。

4

3 回答 3

1

我不太确定你真正想要实现什么,但我希望这会对你有所帮助。

要动态创建对象,请使用new运算符。new运算符总是返回一个指针:

Point* pointObj = new Point();

如果您指定了构造函数,则调用与堆栈上的正常构造非常相似:

Point* pointObj = new Point(x,y);

std::vector在运行时存储对象(动态地在堆中),但不是由它自己创建它们,而是简单地复制它们:

std::vector<Point> vec; //if this object is destructed it contents are destructed aswell

Point pointObj(x,y); //point on stack; will get destructed if it gets out of scope
vec.push_back(pointObj) //copy pointObj to a dynamic location on the heap
于 2012-07-08T18:59:39.533 回答
0

好吧,我不知道您的 Point 构造函数采用什么参数,但您的描述听起来好像您想做这样的事情:

std::vector<Point> MyGlobalPointList;

在你的程序中,你有一些:

MyGlobalPointList.push_back(Point(x,y,color));
于 2012-07-08T18:55:36.323 回答
0

您是否在这里寻找与对象创建相关的自动对象管理?如果是这样,AbstractFactory 可以在这里为您提供帮助。除了工厂是构造对象(点)机制而不是自己到处这样做之外,它还可以执行对象管理,例如在向量中管理它们。

class Point {
  friend class PointFactory;
  Point(int _x, int _y) : x(_x), y(_y) { }
  private:
    ~Point();    //destructor is private
    int x, y;
}

class PointFactory {
  public:
    Point* createPoint() {    //Creates random point
      return createPoint(rand(), rand());
    }
    Point* createPoint(int x, int y) {    //Creates specified point
      Point* p = new Point(x, y);
      points.push_back(p);
      return p;
    }
    void deletePoint(Point *p) {    //p not in use anymore
      std::vector<Point*>::iterator it = std::find(objects.begin(), objects.end(), p);
      if (it != objects.end()) {
        objects.erase(it);
      }
      delete p;
    }
  private:
    std::vector<Point*> objects;
}

int main(...) {
  Point *p = pointFactory.createPoint();    //instead of new Point()
  //use p
  pointFactory.deletePoint(p);    //p not in use anymore
  return 0;
}

希望这是您正在寻找的。

  • 安库尔卫星
于 2012-07-08T19:47:59.133 回答