(原谅提前noob问题)C++:多重继承与多态性
我有4类:
class Person {};
class Student : public Person {};
class Employee : public Person {};
class StudentEmployee : public Student, public Employee {};
本质Person
是基类,其直接由两者Student
和Employee
子类。 StudentEmployee
采用多重继承的子类Student
和Employee
。
Person pat = Person("Pat");
Student sam = Student("Sam");
Employee em = Employee("Emily");
StudentEmployee sen = StudentEmployee("Sienna");
Person ppl[3] = {pat, sam, em};
//compile time error: ambiguous base class
//Person ppl[4] = {pat, sam, em, sen};
当我使用的Person
阵列,基类,我可以把Person
和所有它的子类的此阵列内。除了StudentEmployee
,给出了歧义基类的原因。
鉴于StudentEmployee
保证具有Person
的所有方法和属性,因此StudentEmployee
被认为是Person的一个子类?
- 如果是这样,为什么编译器不允许我将一个对象分配给它的超类型的变量?
- 如果没有,为什么不;那么完成这件事的正确方法是什么?
干杯
编辑:抢先,这个问题是不一样的下面的任一:
polymorphism relates inheritance
Inheritance mucking up polymorphism in C++?
但是,很明显,像这样调用新内存几乎肯定会导致内存泄漏 – Falmarri 2010-08-22 11:13:00
+1的切片。并且为了防止bguiz不知道,这也可能是Person * ppl [] = {&pat,&sam,&em,&sen }; - 这两个选项的内存管理略有不同。 – Michael 2010-08-22 11:19:57
@Falmarri:为什么?你仍然有指针数组。 – Job 2010-08-22 11:31:21