Menu
CoddyTech

回顾:员工层级结构

本课属于 Coddy GDScript 学习旅程的“面向对象编程”单元。第 20 课,共 65 课。

challenge icon

挑战

中等

在五个文件中构建公司的类层次结构。

  • Person:包含 person_name 和 age,由构造函数设置。introduce() 返回 Hi, I'm NAME, AGE years old.
  • Employee 继承 Person,并添加 employee_id(String)和 salary(年薪,int)。重写 introduce(),在父类的文本后添加 My employee ID is ID.。monthly_pay() 返回工资除以 12.0 的结果。
  • Manager 继承 Employee,并添加 department。它的 monthly_pay() 是员工月薪乘以 1.2,而 manage_team() 返回 Managing the DEPARTMENT department.
  • Engineer 继承 Employee,并添加 language。code() 返回 Coding in LANGUAGE.
  • Payroll 有两个静态函数。role(p) 返回 Manager、Engineer、Employee 或 Person,也就是 p 最具体的类。total_monthly(people) 返回所有员工的 monthly_pay() 总和,其中包括经理和工程师。

每个构造函数都会将父类所需的值传给 super(),每个扩展父类结果的重写方法都会使用 super()。

提供的代码会先读取人数,然后逐行读取每个人的信息:person NAME AGE、employee NAME AGE ID SALARY、manager NAME AGE ID SALARY DEPARTMENT 或 engineer NAME AGE ID SALARY LANGUAGE。对于每个人,代码会打印方括号中的角色和 introduce() 的结果、员工的月薪、适用时的 manage_team() 或 code(),最后打印总额。对于 employee Alice 35 E123 60000 和 manager Bob 45 M54 85000 Marketing,输出为:

[Employee] Hi, I'm Alice, 35 years old. My employee ID is E123.
Monthly pay: 5000.00
[Manager] Hi, I'm Bob, 45 years old. My employee ID is M54.
Monthly pay: 8500.00
Managing the Marketing department.
Total monthly payroll: 13500.00

你的代码写在 person.gd、employee.gd、manager.gd、engineer.gd 和 payroll.gd 中。main.gd 存放提供的输入和输出代码,不能编辑。

亲手试试

extends Node

func _ready():
	# 提供的输入和输出代码:保持原样。
	var count := int(OS.read_string_from_stdin())
	var people: Array[Person] = []
	for i in count:
		var p := OS.read_string_from_stdin().split(" ")
		if p[0] == "manager":
			people.append(Manager.new(p[1], int(p[2]), p[3], int(p[4]), p[5]))
		elif p[0] == "engineer":
			people.append(Engineer.new(p[1], int(p[2]), p[3], int(p[4]), p[5]))
		elif p[0] == "employee":
			people.append(Employee.new(p[1], int(p[2]), p[3], int(p[4])))
		else:
			people.append(Person.new(p[1], int(p[2])))
	for person in people:
		print("[%s] %s" % [Payroll.role(person), person.introduce()])
		if person is Employee:
			print("Monthly pay: %.2f" % (person as Employee).monthly_pay())
		if person is Manager:
			print((person as Manager).manage_team())
		elif person is Engineer:
			print((person as Engineer).code())
	print("Total monthly payroll: %.2f" % Payroll.total_monthly(people))

面向对象编程中的所有课

自己练习: GDScript 在线编译器