菱形继承

菱形继承带来的问题

demo

class Person {
public:
	int m_age;
	int m_age1;
	int m_age2;
	int m_age3;
	int m_age4;
	int m_age5;
	int m_age6;
	int m_age7;
	int m_age8;
	int m_age9;
};
// 虚继承
class Student : virtual public Person {
public:
	int m_score;
};
// 虚继承
class Worker : virtual public Person {
public:
	int m_salary;
};

class Undergraduate : public Student, public Worker {
public:
	int m_grade;
};

最底下子类无法访问基类的成员,有二义性

int main() {
	/*
    Undergraduate ug;
	ug.m_grade = 10;
	ug.m_score = 20;
	ug.m_salary = 20;
    ug.m_age = 11; // 会报错
    */

	cout << sizeof(Student) << endl;

	getchar();
	return 0;
}

// 非虚继承:(10 + 10 + 3) * 4 = 23 * 4 // 虚继承:(10 + 2 + 2 + 1) * 4 = 15 * 4

虚继承:

Person类被称为虚基类 demo

demo

demo

Student内存图

demo

Undergraduate内存图

demo