在一个类中创建多个对象
Creating multiple objects in a class
我对如何将大量对象放入一个类感到困惑。 因此,我们需要读取包含时间戳、员工 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;
}
我将省略一些事情,因为这看起来像家庭作业,但这会让你走得更远。
需要注意的几点:
- 您没有使用构造函数。当然,默认构造函数很好,但它可以帮助创建自己的构造函数,尤其是在开始时。
- 您可能应该使用
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
让你弄清楚,应该不难找到
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- 创建对象并防止被破坏
- 在C++中,友元类可以从友元类创建对象吗
- 只在堆中创建C++对象
- 创建用户定义的复制构造函数时无法创建对象