c++支持编写多重继承的代码,一个子类可以拥有多个父类,子类拥有所有父类的成员变量,子类继承所有父类的成员函数,子类对象可以当作任意父类对象使用。
多重继承的本质与单继承相同。
#include <iostream>
#include <string>using namespace std;
class BaseA
{
int ma;
public:
BaseA(int a)
{
ma = a;
}
int getA()
{
return ma;
}
};
class BaseB
{
int mb;
public:
BaseB(int b)
{
mb = b;
}
int getB()
{
return mb;
}
};
class Derived : public BaseA, public BaseB
{
int mc;
public:
Derived(int a, int b, int c) : BaseA(a), BaseB(b) //调用两个父类的构造函数
{
mc = c;
}
int getC()
{
return mc;
}
void print()
{
cout << "ma = " << getA() << ", "
<< "mb = " << getB() << ", "
<< "mc = " << mc << endl;
}
};
int main()
{
cout << "sizeof(Derived) = " << sizeof(Derived) << endl; // 12 成员函数在代码段,所以还是12
d.print();
cout << "d.getA() = " << d.getA() << endl; //继承而来的
cout << "d.getB() = " << d.getB() << endl;
cout << "d.getC() = " << d.getC() << endl;
cout << endl;
BaseA* pa = &d;
BaseB* pb = &d; // pa和pb指向的不一样
cout << "pa->getA() = " << pa->getA() << endl;
cout << "pb->getB() = " << pb->getB() << endl;
cout << endl;
void* paa = pa;
void* pbb = pb; //paa和pbb指向的不一样
if( paa == pbb )
{
cout << "Pointer to the same object!" << endl;
}
else
{
cout << "Error" << endl;
}
cout << "pa = " << pa << endl;
cout << "pb = " << pb << endl;
cout << "paa = " << paa << endl;
cout << "pbb = " << pbb << endl;
return 0;
}
通过多重继承得到的对象可能拥有“不同的地址”! 解决方案:无
derived d(1,2,3);
baseA* pa=&d;
baseB* pb=&d;
pa-->int ma;
int mb; <--pb
int mc;
pa和pb都指向同一个对象,但是指向了不同的位置。
第二个问题:
teacher--->people <----student
doctor-->teacher,student
多重继承可能产生冗余的成员。
#include <iostream>
#include <string>
using namespace std;
class People
{
string m_name;
int m_age;
public:
People(string name, int age)
{
m_name = name;
m_age = age;
}
void print()
{
cout << "Name = " << m_name << ", "
<< "Age = " << m_age << endl;
}
};
class Teacher : virtual public People
{
public:
Teacher(string name, int age) : People(name, age)
{
}
};
class Student : virtual public People
{
public:
Student(string name, int age) : People(name, age)
{
}
};
class Doctor : public Teacher, public Student{
public:
Doctor(string name, int age) : Teacher(name, age), Student(name, age), People(name, age)
{
}
};
int main()
{
Doctor d("Delphi", 33);
d.print();
// d.teacher::print();
// d.student::print();
}
当多重继承关系出现闭合时将产生数据冗余的问题。解决方案:虚继承。
class people();
class teacher:virtual public people();
class student:virtual public people();
class doctor:public teacher,public strdent
{
};
虚继承能够解决数据冗余问题,中间层父类不再关心顶层父类的初始化。
最终子类必须直接调用顶层父类的构造函数。
当架构设计中需要继承时,无法确定使用直接继承还是虚继承。
c++支持多重继承的编程方式,多重继承容易带来问题,可能出现,同一个对象的地址不同的情况,虚继承可以解决数据冗余的问题,虚继承使得架构设计可能出现问题。
最好不用多重继承。