我是oop的初學者,這是我的學習項目。管理公司的模擬器。首先,我不確定我的想法是否正確。我想,我必須手動調用析構函數來保留合適數量的僱傭員工。如果我不這樣做,那麼萬一用戶不想使用生成的人,構造函數將會增加ID
。所以如果有人有更好的想法來解決它,我願意提出建議。我的問題是,根據delete some_new_employee
發生錯誤。我不明白這意味着什麼。我想問任何解釋。在手動調用析構函數期間發生錯誤:表達式必須是指向完整對象類型的指針
class Employee
{
private:
static int ID;
public:
std::string name;
int age;
int id;
Employee::Employee()
{
id = ID++;
}
Employee::~Employee()
{
--id;
}
int Number()
{
return id;
}
};
int Employee::ID = 0;
Employee generate_random_employee(Employee obj)
{
std::vector<std::string> male_names = { "Donald", "Piotr", "James", "Tiny", "Ricky" };
std::vector<std::string> female_names = { "Diana", "Joelle", "Sue", "Karolina" };
std::vector<std::string> lastnames = { "Lester", "Pound", "Park", "Ennis", "Duck",
"Tusk", "Disney", "Jurassic", "Looney-Warde" };
int sex = (rand() % 2) + 0;
if (sex == 1)
{
obj.name = male_names[(rand() % (male_names.size() - 1)) + 0];
}
else
{
obj.name = female_names[(rand() % (female_names.size() - 1)) + 0];
}
obj.name += " " + lastnames[(rand() % (lastnames.size() - 1)) + 0];
obj.age = (rand() % 24) + 25;
return obj;
}
bool are_u_sure()
{
std::string decision;
do
{
std::cout << "Are you sure [Y/N]?" << std::endl;
std::cin >> decision;
if (decision == "y" || decision == "Y")
{
return true;
}
else if (decision == "n" || decision == "N")
{
return false;
}
else
{
std::cout << "Unknow option. Try again." << std::endl;
}
} while (true);
}
int main()
{
std::vector<Employee> employees;
std::string option;
std::cout << "Welcome mrs. manager. What do you want to do today, sir?" << std::endl << std::endl;
do
{
std::cout << "Type .hire to hire a new employee" << std::endl;
std::cin >> option;
if(option == ".hire")
{
Employee some_new_employee;
some_new_employee = generate_random_employee(some_new_employee);
std::cout << "So... do you want to hire a new employee? Let's look at CVs " << std::endl;
std::cout << "I've got one. What do u think about " << some_new_employee.name << " age " << some_new_employee.age << "?" << std::endl;
if (are_u_sure())
{
employees.push_back(some_new_employee);
}
else
{
delete some_new_employee;
}
}
} while (option != ".end");
}
您對分配了'new'的對象調用'delete'。 – PaulMcKenzie
嗯......問題是:我應該如何恰當地銷燬'Employee some_new_employee'創建的對象? – mathsicist
退出模塊時會自動銷燬。你不需要手動調用析構函數。 – PaulMcKenzie