gpt4 book ai didi

c++ - 哪种检查对象类型的方法更好?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:31 26 4
gpt4 key购买 nike

方法 1:

class Employee 
{
public:
virtual int calculateSalary() = 0;

};

class PermanentEmployee : public Employee {
const int salaryPerMonth;
public:
PermanentEmployee(int sal) : salaryPerMonth(sal){}

int calculateSalary() {
return salaryPerMonth;
}
};

class ContractEmployee : public Employee {
const int wagesPerHr;
int totalHour;
public:
ContractEmployee(int sal) : wagesPerHr(sal), totalHour(0){}

void setWorkingDuration(int time) {
totalHour = totalHour + time;
}
int calculateSalary() {
return wagesPerHr * totalHour;
}
};

class Manager {
list<Employee *> ls;
public:
void assignWorkingHour() {
list<Employee *>::iterator it;

for(it = ls.begin(); it != ls.end(); it++) {
Employee *emp = *it;
ContractEmployee* contractEmp = dynamic_cast<ContractEmployee* >(emp);
if(contractEmp) {
contractEmp->setWorkingDuration(5);
}
}
}
};

在问题中,有两种Employee:PermanentEmployeeContractEmployee
有一个名为 Manager 的类,其中包含在他手下工作的所有员工的列表。
对于 ContractEmployee,它必须调用函数 setWorkingDuration(),该函数在类 Manager 的方法 assignWorkingHour 中被调用.

问题是:
这里 Employee 的类型由 dynamic_cast 运算符决定,Manager 必须知道 Employee 的所有派生类类型>.

方法 2:

在类 Employee 中添加另一个成员:

enum TypeOfEmployee {CONTRACT, PERMANENT};

并检查 TypeOfEmployee 以确定 Employee 的类型

请告诉我哪个更好,或者有其他方法吗?

最佳答案

更好的方法是编写不需要确切对象类型知识的代码。在我看来,处理这个问题最优雅的方法是移动 setWorkingDuration()到员工类。大概是这样的:

class Employee
{
public:
// Calculates the salary for this employee.
// Returns the calculated salary.
virtual int calculateSalary() = 0;
// Sets the working duration. Does nothing if the employee is permanent.
// Returns true if Employee is on a contract, false if permanent.
virtual bool setWorkingDuration(int time)
{
return false;
}
};

class PermanentEmployee : public Employee
{
const int salaryPerMonth;
public:
PermanentEmployee(int sal) : salaryPerMonth(sal) {}

int calculateSalary()
{
return salaryPerMonth;
}
};

class ContractEmployee : public Employee
{
const int wagesPerHr;
int totalHour;
public:
ContractEmployee(int sal) : wagesPerHr(sal), totalHour(0) {}

int calculateSalary()
{
return wagesPerHr * totalHour;
}

bool setWorkingDuration(int time)
{
totalHour = totalHour + time;
return true;
}
};

class Manager
{
list<Employee *> ls;
public:
void assignWorkingHours()
{
list<Employee *>::iterator it;
for(it = ls.begin(); it != ls.end(); it++)
{
Employee* emp = *it;
emp->setWorkingDuration(5);
}
}
};

这样,Manager类不必知道 Employee 是否存在实际上是一个 PermanentEmployeeContractEmployee .这就是多态性给你的。一般来说,如果你必须使用 dynamic_cast<> ,您可能想再看一下设计,看看是否可以省略它。

关于c++ - 哪种检查对象类型的方法更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7199991/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com