c++ - 在父类中为多个 child 定义方法

标签 c++ inheritance polymorphism

我有一个父类Person,然后它被EmployeeCustomer继承,这些又被进一步继承。 我还有一个 Person 指针数组,我在其中存储“第 3 级”类。 我希望 salary() 只能由 Employee 访问,而 charge() 只能由 Customer 访问. 尝试在 Person 中使用纯函数,但是 EmployeeCustomer 仍然需要同时定义才能构造。

也许我可以用其他方式定义或以某种方式阻止/删除 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/

相关文章:

c++ - 实现文件中的实例变量——私有(private)与 protected

c++ - 如何知道我的编译器如何编码 float 据?

c++ - 错误 C2678 : binary '!=' : no operator found

c++ - 如何在 C++ 中声明接口(interface)?

c++ - 多重继承指针比较

c++ - 如何在使用 const "this"指针时获取非常量迭代器?

c++ - 使用基类静态常量变量构造基类,我可以这样做吗?

haskell - 如何在 Haskell 98 下编写多态函数

c# - 泛型类型多态性

java - 父类(super class)对象的子类引用