我是面向对象编程的初学者。作为学习项目,我决定创建一个管理公司的小程序。如何计算创建的对象?我读过它但我不明白。我想要告诉我如何使用我的代码作为示例:
class Employee
{
public:
std::string name;
int age;
static int id;
Employee::Employee()
{
id++;
}
};
int Employee::id = 0;
std::ostream& operator<<(std::ostream& out, const std::vector<Employee>& v)
{
out << "[";
for (size_t i = 0; i < v.size(); ++i)
{
out << "ID: " << v[i].id << " Name: " << v[i].name << " age: " << v[i].age;
if (i != v.size() - 1)
out << ", ";
}
out << "]";
return out;
}
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;
}
int main()
{
srand(time(NULL));
std::vector<Employee> employees;
Employee some_new_employee;
for(int i = 0; i < 2; i++)
{
some_new_employee = generate_random_employee(some_new_employee); //randomly generate a new employee. It is Employee type function
employees.push_back(some_new_employee);
}
std::cout << employees << std::endl;
}
目前程序经常将1作为所有对象的ID
答案 0 :(得分:2)
要为每位员工获取唯一ID,请尝试:
class Employee
{
public:
std::string name;
int age;
int id;
static int ID;
Employee()
{
id = ID++;
}
};
int Employee::ID = 0;
std::ostream& operator<<(std::ostream& out, const std::vector<Employee>& v)
{
// ...
return out;
}
主要(简化)
std::vector<Employee> employees;
for(int i = 0; i < 4; i++)
{
Employee e;
employees.push_back(e);
}
std::cout << employees << std::endl;
输出:
[ID: 0 Name: age: 0, ID: 1 Name: age: 0, ID: 2 Name: age: 0, ID: 3 Name: age: 0]
关键思想:对象的每个实例都需要一个唯一的 id。静态正好相反......所有实例的共同值。
ctor设置自己的id并增加静态ID。
请注意,ID表示已构建的数量,但不包含可能存在的数量(考虑析构函数,临时值,副本等)。
答案 1 :(得分:2)
generate_random_employee(some_new_employee);
employees.push_back(some_new_employee);
这些行都没有调用构造函数。
您应该重载赋值运算符或复制构造函数以增加计数。
并且您无法获得静态ID ...静态意味着您的所有实例都具有相同的ID ...
你想要一个satic计数器并用它来分配构造中的id。