设计父结构体—员工。子结构体:工人,农民,教师,科学家(scientist),服务生。
(1)其中工人,农民,服务生只有基本工资。(10分)
(2)教师除基本工资外,还有课酬(元/天)。(10分)
(3)科学家除基本工资外,还有年终奖。(10分)
编写一个测试结构体,将各种类型的员工的全年工资打印出来。(10分)
代码示例:
package main
import (
"fmt"
"unsafe"
)
type Employee struct {
//基本工资
BaseWage float64
eType E_TYPE //员工类型
}
type E_TYPE string
const (
WORKER E_TYPE = "工人"
FARMER = "农民"
TEACHER2 = "老师"
SCIENTIST = "科学家"
WAITER = "服务员"
)
type Worker struct {
Employee
}
func (e *Employee) getYearBaseSalary() float64 {
return 12 * e.BaseWage
}
func (e *Employee) PrintSalary() {
fmt.Printf("%s全年工资:", e.eType)
switch e.eType {
case WORKER:
fallthrough
case FARMER:
fallthrough
case WAITER:
fmt.Printf("%.2f\n", e.BaseWage)
case TEACHER2:
//下面使用unsafe包的Pointer将父类(Employee)实例转为子类(Teacher2)实例
//将父类实例转为通用指针
uP := unsafe.Pointer(e)
//再转换为本地 Teacher2 结构体
pT := (*Teacher2)(uP)
//转换完毕,可以输出子类特有属性
fmt.Println("测试-->老师的课酬是:", pT.ClassRemuneration)
fmt.Printf("%.2f\n", e.getYearBaseSalary()+pT.ClassRemuneration)
case SCIENTIST:
uP := unsafe.Pointer(e)
pT := (*Scientist)(uP)
fmt.Printf("%.2f\n", e.getYearBaseSalary()+pT.YearEndBonus)
default:
fmt.Println("未能匹配到对应的员工类型")
}
}
type Farmer struct {
Employee
}
type Teacher2 struct {
Employee
//课酬 (元/天)
ClassRemuneration float64
}
type Scientist struct {
Employee
//年终奖
YearEndBonus float64
}
type Waiter struct {
Employee
}
//----------------测试------------------------
func main() {
//实例化工人
var worker *Worker = &Worker{Employee: Employee{BaseWage: 120, eType: WORKER}}
//实例化农民
var farmer *Farmer = &Farmer{
Employee: Employee{
BaseWage: 150,
eType: FARMER,
},
}
//实例化老师
employee := &Employee{BaseWage: 250, eType: TEACHER2}
var teacher2 *Teacher2 = &Teacher2{Employee: *employee}
teacher2.ClassRemuneration = 500
//实例化科学家
var scientist *Scientist = &Scientist{
Employee{BaseWage: 300, eType: SCIENTIST},
200,
}
//实例化服务人员
var waiter *Waiter = &Waiter{Employee: Employee{BaseWage: 150, eType: WAITER}}
//测试输出
worker.PrintSalary()
farmer.PrintSalary()
waiter.PrintSalary()
teacher2.PrintSalary()
scientist.PrintSalary()
}
运行结果:
从以上代码中可以看到,我们没有使用接口,给父类绑定一个方法PrintSalary,子类就都可以使用这个方法了,然后在该方法内对父类型强转成了子类型。
有疑问加站长微信联系(非本文作者)