2014-02-27 73 views
0

我定義了一個名爲HPC_user類,如下所示:如何分配類對象的數組

#include <iostream.h> 
#include <string> 

using std::string; 

class HPC_user 
{ 
    public: 
    HPC_user(std::string firstName, std::string lastName, std::string login, std::string school, double activity); 
    ~HPC_user(); 

    std::string get_first() const { return fName; } 
    void set_first(std::string first) { fName = first; } 

    std::string get_last() const { return lName; } 
    void set_last(std::string last) { lName = last; } 

    std::string get_login() const { return uId; } 
    void set_login(std::string login) { uId = login; } 

    std::string get_school() const { return sName; } 
    void set_school(std::string school) { sName = school; } 

    std::string get_activity() const {return cpuTime; } 
    void set_activity(std::string activity) { cpuTime = activity; } 

    private: 
    std::string fName, lName, uId, sName, cpuTime; 
}; 


HPC_user.cpp 
#include "HPC_user.h" 

// constructor of HPC_user                                        

HPC_user::HPC_user(std::string firstName, std::string lastName, std::string login, std::string school, double activity) 
{ 
    fName = firstName; 
    lName = lastName; 
    uId = login; 
    sName = school; 
    cpuTime = activity; 

    // cout << "new HPC_user created\n";                                     
} 

HPC_user::~HPC_user() // destructor 

現在我想分配500個HPC_user對象的數組,並設置元件爲NULL或0.0第一。然後在for循環中分配實際值。

這是我做過什麼:

int size = 500; 
    HPC_user *users; 
    users = new HPC_user(NULL,NULL,NULL,NULL,0.00)[size]; 

我在編譯時就發生錯誤:

db2class.cpp:51:49: error: expected ';' after expression 
users = new HPC_user(NULL,NULL,NULL,NULL,0.00)[size]; 

什麼是爲對象數組分配空間的正確方法?

+0

的[動態分配對象的數組(HTTP可能重複:// stackoverflow.com/questions/255612/dynamically-allocating-an-array-of-objects) – drahnr

回答

1

使用的std::vector

std::vector<HPC_user> users(size, HPC_user(NULL,NULL,NULL,NULL,0.00)); 

但是,這將立即崩潰,因爲從一個空指針初始化std::string是錯誤的。所以,你需要修復的構造函數的參數是什麼明智的,或者提供一個合理的默認構造函數

HPC_user() : activity(0.0) {} // strings get default constructed to "" 

,做

std::vector<HPC_user> users(size); 
+0

@ Jarod42很好,謝謝! – juanchopanza

+0

謝謝,把它作爲一個向量而不是數組在這裏有什麼好處? – ddd

+1

如果需要,更安全,更易於編寫和讀取和維護,更短的代碼,異常安全,值語義,可能更快,可以增長和縮小... std :: vector是C++中的默認收集機制。 –

1

如果你認爲你HPC_user有一個合理的默認值,添加一個默認的構造函數這個類:

HPC_user::HPC_user() 
    : cpuTime(0.0) 
{ 
} 

然後你就可以構建500 HPC_user的載體:

std::vector<HPC_user> users(500); 

而且你應該使用初始化語法,初始化數據時,不分配:

HPC_user::HPC_user(std::string firstName, std::string lastName, std::string login, std::string school, double activity) 
    : fName(firstName) 
    , lName(lastName) 
    , uId(login) 
    , sName(school) 
    , cpuTime(activity) 
{ 
} 
+0

我可以在我的HPC_user類聲明中執行此操作嗎? HPC_user(std :: string firstName =「」,std :: string lastName =「」,std :: string login =「」,std :: string school =「」,double activity = 0.0); – ddd

+0

是的。你可以,但你真的不應該這樣做,因爲這會在呼叫方造成很大的開銷。我錯過了cpuTime是雙倍的,在這種情況下它必須被初始化。對於字符串,它們有合理的默認構造函數。 –