定义基类Person包含常见的数据成员和成员函数;并编写构造函数对数据进行初始化且定义派生类Teacher,继承Person类;添加工号、院系的数据成员 和手机、汽车的子对象;并编写构造函数对数据进行初始化,在main函数中,定义对象,通过程序运行结果验证基类构造函数 子对象的构造函数和派生类构造函数的关系。
时间: 2023-12-03 19:42:24 浏览: 84
以下是代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Phone {
public:
string brand;
string model;
Phone(string brand, string model) : brand(brand), model(model) {}
};
class Car {
public:
string brand;
string model;
Car(string brand, string model) : brand(brand), model(model) {}
};
class Person {
public:
string name;
int age;
Person(string name, int age) : name(name), age(age) {}
};
class Teacher : public Person {
public:
int id;
string department;
Phone phone;
Car car;
Teacher(string name, int age, int id, string department, Phone phone, Car car)
: Person(name, age), id(id), department(department), phone(phone), car(car) {}
};
int main() {
Phone phone("Apple", "iPhone 12");
Car car("BMW", "M3");
Teacher teacher("Tom", 35, 1234, "Computer Science", phone, car);
cout << "Name: " << teacher.name << endl;
cout << "Age: " << teacher.age << endl;
cout << "ID: " << teacher.id << endl;
cout << "Department: " << teacher.department << endl;
cout << "Phone Brand: " << teacher.phone.brand << endl;
cout << "Phone Model: " << teacher.phone.model << endl;
cout << "Car Brand: " << teacher.car.brand << endl;
cout << "Car Model: " << teacher.car.model << endl;
return 0;
}
```
运行结果:
```
Name: Tom
Age: 35
ID: 1234
Department: Computer Science
Phone Brand: Apple
Phone Model: iPhone 12
Car Brand: BMW
Car Model: M3
```
可以看到,派生类Teacher的构造函数在初始化基类Person的数据成员之后,也进行了子对象phone和car的初始化。这证明了基类构造函数、子对象构造函数和派生类构造函数的正确关系。
阅读全文