qfedu-cpp-level/day5/d4.cpp

52 lines
1.0 KiB
C++
Raw Normal View History

2023-08-14 17:20:39 +08:00
// 构造函数
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Person
{
private:
string name;
int age;
public:
Person(const string &name, int age) : name(name), age(age) {}
public:
void hi()
{
cout << this->name << ", " << this->age << endl;
}
};
class Worker : public Person
{
private:
int salary; // 工资
int year; // 工作年限
public:
// 子类的构造函数定义时,可以调用父类的构造函数进行父类成员的初始化
// 使用初始化列表实现(调用父类的构造函数,传入对应参数)
Worker(const string &name, int age, int salary, int year) : Person(name, age), salary(salary), year(year)
{
}
public:
void hi() // 重写了父类的函数,覆盖了父类的 hi()
{
// 先调用父类的 hi()
Person::hi();
cout << salary << ", " << year << endl;
}
};
int main()
{
Worker w1 = Worker("liming", 18, 2100, 2);
w1.hi();
return 0;
}