首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何分配类对象的数组

如何分配类对象的数组
EN

Stack Overflow用户
提问于 2014-02-27 15:56:07
回答 1查看 123关注 0票数 0

我将一个名为HPC_user的类定义为:

代码语言:javascript
复制
#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循环中赋值。

我就是这样做的:

代码语言:javascript
复制
  int size = 500;
  HPC_user *users;
  users = new HPC_user(NULL,NULL,NULL,NULL,0.00)[size];

我编译它时出错了:

代码语言:javascript
复制
db2class.cpp:51:49: error: expected ';' after expression
users = new HPC_user(NULL,NULL,NULL,NULL,0.00)[size];

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

EN

回答 1

Stack Overflow用户

发布于 2014-02-27 15:58:49

如果您认为您的HPC_user有合理的缺省值,请向该类添加一个默认构造函数:

代码语言:javascript
复制
HPC_user::HPC_user()
   : cpuTime( 0.0 )
{
}

然后,您可以构造一个500 HPC_user的向量:

代码语言:javascript
复制
std::vector< HPC_user > users( 500 );

当您初始化数据时,您应该使用初始化语法,而不使用任何辅助:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22073671

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档