【发布时间】:2021-07-07 16:36:44
【问题描述】:
为什么在代码中使用了指向指针而不是单指针?另外你认为析构函数写错了,如果我怎样才能使它正确?
指向指针的指针:employee** _arr;
你可以看到下面的代码:
#include<iostream>
class employee {
private:
std::string _name;
std::string _surname;
int _year;
double _salary;
static int numberOfEmployees;
public:
employee() {
_name = "not-set";
_surname = "not-set";
_year = 0;
_salary = 0;
numberOfEmployees++;
}
employee(int year, std::string name, std::string surname) {
_name = name;
_surname = surname;
_year = year;
numberOfEmployees++;
calculateSalary();
}
void calculateSalary() {
//salary = 2310 + 2310 * year * 12/100.0
_salary = 2310 + (2310 * (double)_year) * (12 / 100.0);
}
void printInfo() {
std::cout << _name << " " << _surname << " " << _year << " " << " " << _salary << " TL/month" << std::endl;
}
static int getEmployeeCount() {
return numberOfEmployees;
}
};
class employeeList {
private:
int _size;
int _lenght;
employee** _arr;
public:
employeeList() :_size(1), _lenght(0), _arr(NULL) {}
employeeList(int size) :_size(size) {
_arr = new employee * [_size];
_lenght = 0;
}
int listLength() {
return _lenght;
}
employee retrieve_employeeFromIndex(int index) {
if (index >= 0 && index < _size) {
return *_arr[index];
}
}
void addToList(employee* item) {
_lenght++;
if (_lenght <= _size) {
_arr[_lenght - 1] = item;
}
else {
std::cout << "you cannot add another employee!";
}
}
static void printEmployees(employeeList el) {
for (int i = 0; i < el._lenght; i++) {
el._arr[i]->printInfo();
}
}
~employeeList() {
delete[] _arr;
}
};
int employee::numberOfEmployees = 0;
int main() {
employee a;
employee b(5, "John", " Doe");
employee c(3, "Sue", "Doe");
employeeList empList(employee::getEmployeeCount());
empList.addToList(&a);
empList.addToList(&b);
empList.addToList(&c);
employeeList::printEmployees(empList);
std::cout << empList.listLength() << std::endl;
return 0;
}
你可以看到输出:
为什么在代码中使用了指向指针而不是单指针?另外你认为析构函数写错了,如果我怎样才能使它正确?
【问题讨论】:
-
为什么在代码中使用指向指针的指针而不是单个指针? -- 代码中不需要任何指针。
std::vector<employee>是employeList,而static int numberOfEmployees;不再需要。 -
将指向本地对象的指针放入列表中...灾难的秘诀。
-
看看你的
retrieve_employeeFromIndex函数。如果索引超出范围,你会返回什么? -
要回答原始问题,您需要指向对象的指针数组,而不是指向单个对象的指针。
标签: c++ pointers destructor pointer-to-pointer