• go 接口方和类方法 计算薪资


    package main
    
    import("fmt")
    
    type Programer struct {
    	name string
    	base float32
    	extra float32
    }
    
    func (p Programer) CalcSalary() float32 {
    	return p.base
    }
    
    type Sale struct {
    	name string
    	base float32
    	extra float32
    }
    
    type Employer interface {
    	CalcSalary() float32
    }
    
    func (p Sale) CalcSalary() float32 {
    	return p.base + p.extra*p.base*0.5
    }
    
    func NewProgramer(name string, base ,extra float32) Programer {
    	return Programer {
    		name:name,
    		base:base,
    		extra:extra,
    	}	
    }
    
    func NewSale(name string, base,extra float32) Sale  {
    	return Sale {
    		name:name,
    		base:base,
    		extra:extra,
    	}	
    }
    
    func calcAll(e []Employer) float32{
    	var cost float32
    	for _, v := range e {
    		cost = cost + v.CalcSalary()
    	}
    	return cost
    
    }
    
    func main(){
    	p1 := NewProgramer("搬砖1",15000.0,0.0)
    	p2 := NewProgramer("搬砖2",16000.0,0.0)
    	p3 := NewProgramer("搬砖3",17000.0,0.0)
    
    	s1 := NewSale("销售1",1000.0,2.5)
    	s2 := NewSale("销售2",1100.0,2.5)
    	s3 := NewSale("销售3",1200.0,2.5)
    	
    	var employList []Employer           // 切片的接口类型
    	employList = append(employList, p1) // 由于这些对象都实现了接口方法, 可以把这些对象放入接口切片中
    	employList = append(employList, p2)
    	employList = append(employList, p3)
    	employList = append(employList, s1)
    	employList = append(employList, s2)
    	employList = append(employList, s3)
    	cost := calcAll(employList)
    	fmt.Printf("这个月的总工资%f",cost)
    }
    
  • 相关阅读:
    Java练习题
    循环练习
    Java String类详解
    Collections类
    TreeSet类
    IOS基础:NSTimer类的使用
    IOS基础:深入理解Objectivec中@class的含义
    IOS基础:retain,copy,assign及autorelease
    IOS基础:ActionSheet(上拉菜单)的实现
    Xcode 模拟器生成目标目录位置查找
  • 原文地址:https://www.cnblogs.com/heris/p/16023242.html
Copyright © 2020-2023  润新知