【发布时间】:2016-03-07 10:56:07
【问题描述】:
我必须上课,一个Employee 课程和一个BankAccount 课程,员工课程有BankAccount 课程作为私有变量指针。
这就是我想要做的:
- 我需要为每个
Employee中的所有BankAccounts 设置值 - 然后我删除函数末尾的每个
Employee的所有BankAccounts。
我使用Employee 中的成员函数设置器来设置BankAccount 指针。 BankAccount 有一个私有变量,即金额。稍后我在应该指向每个BankAccount's 内存地址的指针上调用delete。在我调用 print 查看每个 Employee 的银行值之后,它仍在打印每个 BankAccount 的值
如果我调用 delete 是否不应该删除堆上的内存并且调用 print 时不会为 BankAccount 输出任何内容?
代码如下:
vector<Employee*> employees;
//get employee full name & salary and return
employees.push_back(get_employee_info());
//setup their bank account
setup_bank(employees);
//make temp pointer to store bank memory address
BankAccount * tempBankPtr;
for (int i =0; i < employees.size(); i++) {
tempBankPtr =employees[i]->get_bank();
delete tempBankPtr // delete the heap object that pointer is pointing at
}
//print values
for (int i =0; i< employees.size(); i++) {
employees[i]->print();
}
打印代码
void Employee:: print() const {
cout << "First name is: " << firstName << "\n";
cout << "Last name is: " << lastName << "\n";
BankAccount* bankholder = NULL;
bankholder = get_bank();
if(bankholder != NULL)
cout << "Account Balance is: " << get_bank()->get_amount() << "\n"; //prints values
}
银行吸气剂
BankAccount* Employee::get_bank() const{
return bank;
}
这在 setup_bank 中调用
void Employee::set_bank(Employee* e, double amount){
bank = new BankAccount(amount);
}
【问题讨论】:
标签: c++ pointers memory heap-memory