我将一个名为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];为对象数组分配空间的正确方法是什么?
发布于 2014-02-27 15:58:49
如果您认为您的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 )
{
}https://stackoverflow.com/questions/22073671
复制相似问题