如何分配类对象数组

时间:2014-02-27 15:56:07

标签: c++ arrays

我定义了一个名为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];

为对象数组分配空间的正确方法是什么?

2 个答案:

答案 0 :(得分: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 )
{
}

答案 1 :(得分: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);