我有一个父类Person
,然后它被Employee
和Customer
继承,并且它们进一步被继承。
另外,我有一个Person
指针数组,用于存储“第三级”类。
我希望salary()
仅可以访问Employee
,charge()
仅可以访问Customer
。
试图在Person
中使用纯函数,但是Employee
和Customer
仍然需要同时定义两者才能构造。
也许我可以用其他方式定义,或者以某种方式阻止/删除儿童中不需要的功能?
class Person {
public:
int money;
Person() { money = 1000; }
virtual ~Person() {}
void salary(int m) { if (m >= 0) money += m; }
void charge(int m) { if (m >= 0) money -= m; }
};
class Employee : public Person {};
class Customer : public Person {};
class Programmer : public Employee {};
class Secretary : public Employee {};
class Janitor : public Employee {};
class Business : public Customer {};
class Private : public Customer {};
class Charity : public Customer {};
编辑:
Person* people[10];
Person[0] = new Programmer();
...
然后我想使用这些指针来调用方法,例如(*person[0]).salary(100)
(代表从员工派生)或(*person[5]).charge(500)
(代表客户)。
我使用类型转换来确定对象是来自E还是来自C。
答案 0 :(得分:1)
由于类型擦除,无法在编译时完成此操作,但是您可以在运行时执行。
首先,在相关类而不是基类中定义函数:
class Person {
// no salary or change
};
class Employee : public Person {
public:
virtual void salary(int m)
{
// ...
}
};
class Customer : public Person {
public:
virtual void change(int m)
{
// ...
}
};
然后,如果您已经知道Person*
指向雇员,请使用static_cast
:
static_cast<Employee*>(people[0])->salary(100);
如果您不知道,请使用dynamic_cast
:
if (auto* employee = dynamic_cast<Employee*>(people[0])) {
employee->salary(100);
} else {
// report error
}
答案 1 :(得分:1)
我不确定这是否可以按照您的要求解决,但我会为您解决:
class Person {
public:
int money;
Person() { money = 1000; }
virtual ~Person() {}
};
// providing the methods as specialization to the Employee and Customer classes
class Employee : public Person {
public:
void salary(int m) { if (m >= 0) money += m; }
};
class Customer : public Person {
public:
void charge(int m) { if (m >= 0) money -= m; }
};
class Programmer : public Employee {};
class Secretary : public Employee {};
class Janitor : public Employee {};
class Business : public Customer {};
class Private : public Customer {};
class Charity : public Customer {};
现在,您可以确保只有员工可以使用工资方式,而客户可以使用费用方式。但是在访问时,您必须写一张支票:
Person* people[10];
people[0] = new Programmer();
// while accessing you need to make sure that it is type employee!!
if (auto employee = dynamic_cast<Employee*>(people[0])) {
employee->salary(100)
}
对客户也一样!!
别忘了为<typeinfo>
加入dynamic_cast
!