2014-02-27 74 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是双倍的,在这种情况下它必须被初始化。对于字符串,它们有合理的默认构造函数。 –