我想了解派生类中纯虚函数的行为,将其传递给与(抽象)基类相同类型的参数时。
为了澄清这个问题,我从GeeksForGeeks中获取了以下代码并对其进行了修改:
namespace example {
enum Type {ENGINEER, MANAGER};
class Employee
{
private:
const Type worker;
public:
Employee(const Type& worker) : worker(worker) {}
virtual ~Employee {}
virtual void raiseSalary(const Employee&) = 0;
{ /* common raise salary code */ }
virtual void promote(const Employee&) = 0;
{ /* common promote code */ }
};
class Manager: public Employee {
private:
int degree;
public:
//<constructor>\\
virtual void raiseSalary(const Employee&)
{ /* Manager specific raise salary code, may contain
increment of manager specific incentives*/ }
virtual void promote(const Employee&)
{ /* Manager specific promote */ }
};
}
现在,我们如何才能访问degree
派生类中的字段Manager
以更新他的degree
?由于传递给的参数raiseSalary(Employee& employee)
可能是Manager
或Engineer
我认为有两种方法可以解决该问题。让我们从一个非常糟糕的解决方案开始:使用强制转换。在那种情况下dynamic_cast
。您可以尝试向下转换类型。如果dynamic_cast
无法做到这一点,它将返回一个空指针或引发异常(取决于您转换的指针还是值/引用类型)。但是随着越来越多的经理,工程师类型的出现,这种方法将迫使您调整自己的演员表。您可能还需要使用friend
来允许特定的类访问其他内部类。friend
不会在层次结构中被继承,因此您最终将有很多朋友=>破碎,破碎,破碎:(
一种替代方法是使用“访客模式”:http : //en.wikipedia.org/wiki/Visitor_pattern使用访客模式,您还可以使基本的无操作访客和更细粒度的访客处理特定内容。只是一个小例子(没有特定派生的访客):
namespace example {
class SalaryRaisingVisitor;
class EmployeePromotingVisitor;
class Employee
{
public:
Employee() {}
//don't forget to implement the copy constructor: read more about rule of 3!!!
virtual ~Employee {}
virtual void accept(SalaryRaisingVisitor const&) = 0;
virtual void accept(EmployeePromotingVisitor const&) = 0;
};
class Manager: public Employee {
private:
int degree;
public:
//<constructorS>
virtual void accept(SalaryRaisingVisitor const& v)
{
v.visit(*this, degree);
}
virtual void accept(EmployeePromotingVisitor const& v)
{
v.visit(*this, degree);
}
};
class Engineer: public Employee {
public:
//<constructorS>
virtual void accept(SalaryRaisingVisitor const& v)
{
v.visit(*this);
}
virtual void accept(EmployeePromotingVisitor const& v)
{
v.visit(*this);
}
};
class SalaryRaisingVisitor
{
void visit(Manager& m, int& degree) //might be const if no internal state changes
{
//...
}
void visit(Engineer& e) //might be const if no internal state changes
{
//...
}
};
}
最后,在处理C ++时,请尝试避免使用虚函数:)并将所有内容移至静态多态性:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句