【发布时间】:2019-10-25 09:47:44
【问题描述】:
我有一个父类Person,然后被Employee和Customer继承,这些又被进一步继承。
我还有一个Person 指针数组,我在其中存储“第三级”类。
我希望salary() 只能由Employees 访问,charge() 只能由Customers 访问。
尝试在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。
【问题讨论】:
标签: c++ inheritance polymorphism