我有一个父类Person
,然后它被Employee
和Customer
继承,这些又被进一步继承。
我还有一个 Person
指针数组,我在其中存储“第 3 级”类。
我希望 salary()
只能由 Employee
访问,而 charge()
只能由 Customer
访问.
尝试在 Person
中使用纯函数,但是 Employee
和 Customer
仍然需要同时定义才能构造。
也许我可以用其他方式定义或以某种方式阻止/删除 child 不需要的功能?
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)
派生自 Employee 或 (*person[5]).charge(500)
派生自 Customers。
我使用转换来了解对象是来自 E 还是 C。
最佳答案
由于类型删除,这不能在编译时完成,但您可以在运行时完成。
首先,在相关类而不是基类中定义函数:
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
}
关于c++ - 在父类中为多个 child 定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58556095/