多继承

C++允许一个类可以有多个父类(不建议使用,会增加程序设计复杂度)

代码示例:

#include <iostream>
using namespace std;

class Student {
public:
	int m_score;
	Student(int score = 0) :m_score(score) { }
	void study() {
		cout << "Student::study() - score = " << m_score << endl;
	}
	~Student() {
		cout << "~Student" << endl;
	}
};

class Worker {
public:
	int m_salary;
	Worker(int salary = 0) :m_salary(salary) { }
	void work() {
		cout << "Worker::work() - salary = " << m_salary << endl;
	}
	~Worker() {
		cout << "~Worker" << endl;
	}
};

class Undergraduate : public Student, public Worker {
public:
	int m_grade;
    // 构造函数调用父类的构造函数
	Undergraduate(
		int score = 0, 
		int salary = 0, 
		int grade = 0) :Student(score), Worker(salary), m_grade(grade) {

	}
	void play() {
		cout << "Undergraduate::play() - grade = " << m_grade << endl;
	}
	~Undergraduate() {
		cout << "~Undergraduate" << endl;
	}
};

int main() {
	{ // 会调用析构函数 
		Undergraduate ug;
		ug.m_score = 100;
		ug.m_salary = 2000;
		ug.m_grade = 4;
		ug.study();
		ug.work();
		ug.play(); 
	}

	cout << sizeof(Undergraduate) << endl;

	getchar();
	return 0;
}

多继承体系下的构造函数调用,代码如上Undergraduate

多继承-虚函数

如果子类继承的多个父类都有虚函数,那么子类对象就会产生对应的多张虚表

class Student {
public:
	virtual void study() {
		cout << "Student::study()" << endl;
	}
};

class Worker {
public:
	virtual void work() {
		cout << "Worker::work()" << endl;
	}
};

class Undergraduate : public Student, public Worker {
public:
	void study() {
		cout << "Undergraduate::study()" << endl;
	}
	void work() {
		cout << "Undergraduate::work()" << endl;
	}
	void play() {
		cout << "Undergraduate::play()" << endl;
	}
};

int main() {
	/*Undergraduate ug;
	ug.study();
	ug.work();
	ug.play();*/

	Student *stu = new Undergraduate();
	stu->study();

	Worker *worker = new Undergraduate();
	worker->work();

	cout << sizeof(Undergraduate) << endl;

	getchar();
	return 0;
}

demo