2012-07-08 27 views
0

我有一個程序可以在整個程序中散佈點隨機數量的點。當它運行時,我還想爲每個點創建一個對象並將其存儲在向量中。我創建了一個具有各種屬性的Point類,但我不知道如何實現上述內容。在研究處理類似但不相同的問題的其他問題時,會使用指針,但同樣,我不知道如何實現它們。在沒有用戶輸入的情況下創建動態對象

+0

什麼是你運行的第一個問題爲,當您試圖實現它? – 2012-07-08 18:55:03

回答

1

我不太清楚你真的想達到什麼,但我希望這會幫助你。

使用new運算符創建對象。如果您指定一個構造函數的調用非常相似,正常施工堆棧

Point* pointObj = new Point(); 

:該new操作總是返回一個指針

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 
+0

不要忘記用'new'創建的任何東西都要刪除'! – Linuxios 2012-07-08 19:14:16

+0

謝謝,這正是我需要的! – Behemyth 2012-07-08 22:10:20

0

好了,我不知道什麼參數的點構造需要,但你的描述聽起來好像你想要做這樣的事情:

std::vector<Point> MyGlobalPointList; 

和你的程序中,你有其中的幾個:

MyGlobalPointList.push_back(Point(x,y,color)); 
0

您是否在尋找自動對象管理與objec綁在這裏創造?如果是這樣,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; 
} 

希望這是你在找什麼。

  • ANKUR Satle
+0

這不是非常有用的國際海事組織。一個'std :: vector '(而不是'std :: vector ''幾乎和你的包裝類一樣。唯一的區別是對象缺少創建,但是因爲沒有這個要求,所以你的「工廠」是沒有實現多態我會說除了很多樣板代碼之外的確沒有區別。 – Paranaix 2012-07-08 19:53:26

相關問題