在一个类中创建多个对象

Creating multiple objects in a class

本文关键字:创建 对象 一个      更新时间:2023-10-16

我对如何将大量对象放入一个类感到困惑。 因此,我们需要读取包含时间戳、员工 ID、位置编号、事件代码的文件。输入的示例如下:

10039865 WHITE99 1 OP
10039876 WHITE99 1 EN
10047500 PINK01 1 EN
10047624 SMITH01 3 EX
10047701 TAN07 2 EN
10048567 DIITZ01 2 OP
10048577 DIITZ01 2 OP
10048587 DIITZ01 2 OP

如何将这些信息设置为类中的对象? 这是我到目前为止得到的,并从这里卡住。我们需要使用指向对象的指针数组编写程序。

class Employee {
long timestamp;
string staffID;
int locNum;
string eventCode;
public:
void setValues (long, string, int, string);
};
void Employee::setValues(long timestamp, string staffID, int locNum, string eventCode) {
this->timestamp = timestamp;
this->staffID = staffID;
this->locNum = locNum;
this->eventCode = eventCode;
}

我将省略一些事情,因为这看起来像家庭作业,但这会让你走得更远。

需要注意的几点:

  1. 您没有使用构造函数。当然,默认构造函数很好,但它可以帮助创建自己的构造函数,尤其是在开始时。
  2. 您可能应该使用vector而不是array

例如:

// Note that I'm making the members public - this is only for demonstration so I don't have to write getters and setters.
class Employee {
public:
Employee(long, std::string, int, std::string);
long timestamp;
std::string staffID;
int locNum;
std::string eventCode;
};
// Here is the constructor.
Employee::Employee(long l, std::string s, int n, std::string s2): timestamp(l), staffID(s), locNum(n),  eventCode(s2){}

至于数组 - 坚持使用员工指针向量可能更明智。如:

typedef Employee * EmployeePointer;    
EmployeePointer employeePtr;
std::vector<EmployeePointer> employeeVec;

然后.push_back()新员工使用带有指针的花哨的新构造函数。

employeePtr = new Employee(181213, "Bob", 22, "OP");
employeeVec.push_back(employeePtr);

只需为新员工重复使用employeePtr即可。

employeePtr = new Employee(666732, "Sue", 21, "MA");
employeeVec.push_back(employeePtr);

您将看到创建了一个指向员工对象的指针向量(大多数其他语言无论如何都将其称为数组(:

for(auto it = employeeVec.begin(); it != employeeVec.end(); it++){
std::cout << (*it)->timestamp << " " << (*it)->staffID << " " << (*it)->locNum << " " << (*it)->eventCode << std::endl;
}

其中显示:

181213 Bob 22 OP
666732 Sue 21 MA

如果您出于某种原因无法使用vector那么使用数组实现这一点并没有什么不同,除了。

EmployeePointer empPtrArr;
// You'll need to know the size of your array of pointers or else dynamically allocate it, which I don't think you want to do.
empPtrArr = * new EmployeePointer[2];

而且你必须使用一个基本的for循环,而不是我用的那么花哨for(auto ... )


结语:

  • 对于每个"新"都有一个"删除",否则您将有内存泄漏
  • 我至少有一个#include让你弄清楚,应该不难找到