C++ 在父类中为多个子类定义方法
我有一个父类C++ 在父类中为多个子类定义方法,c++,inheritance,polymorphism,C++,Inheritance,Polymorphism,我有一个父类Person,然后它被Employee和Customer继承,这些都是进一步继承的。 我还有一个Person指针数组,在这里我存储“第三级”类。 我希望salary()只能由Employees访问,而charge()只能由Customers访问。 尝试在Person中使用纯函数,但是Employee和Customer仍然需要定义这两个函数来构造 也许我可以用其他方式定义,或者以某种方式阻止/删除子对象中不需要的函数 class Person { public: int mon
Person
,然后它被Employee
和Customer
继承,这些都是进一步继承的。
我还有一个Person
指针数组,在这里我存储“第三级”类。
我希望salary()
只能由Employee
s访问,而charge()
只能由Customer
s访问。
尝试在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[0])。对于派生自员工的薪酬(100)
,或者对于客户的薪酬(500)。
我使用强制转换来确定对象是来自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)
{
// ...
}
};
然后,如果您已经知道人员*
指向员工,请使用static\u cast
:
static_cast<Employee*>(people[0])->salary(100);
if (auto* employee = dynamic_cast<Employee*>(people[0])) {
employee->salary(100);
} else {
// report error
}
我不确定这是否能满足您的要求,但我将为您提供一个解决方案:
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)
}
人*people[10];
人员[0]=新程序员();
//在访问时,您需要确保它是employee!!
if(自动员工=动态员工(人员[0])){
员工->工资(100)
}
同样对于客户也是
不要忘了为动态演员设置
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)
}