paizaの練習問題を解く クラスの継承 Go編
こんにちは、ナナオです。 前回に引き続き競プロを実施していきたいと思います。 今回の問題は以下です。 クラスの継承 | レベルアップ問題集 | プログラミング学習サイト【paizaラーニング】 実装 以下のように実装しました。 package main import "fmt" type Customer interface { OrderAlCohol(amount int) OrderSoftdrink(amount int) OrderFood(amount int) GetTotalAmount() int } type Children struct { TotalAmount int } func (c *Children) OrderAlCohol(amount int) { return } func (c *Children) OrderSoftdrink(amount int) { c.TotalAmount += amount } func (c *Children) OrderFood(amount int) { c.TotalAmount += amount } func (c *Children) GetTotalAmount() int { return c.TotalAmount } type Adult struct { Children HasOrderedAlcohol bool } func (a *Adult) OrderAlCohol(amount int) { a.TotalAmount += amount a.HasOrderedAlcohol = true } func (a *Adult) OrderSoftdrink(amount int) { a.TotalAmount += amount } func (a *Adult) OrderFood(amount int) { if a.HasOrderedAlcohol { a.TotalAmount += amount - 200 } else { a.TotalAmount += amount } } func main(){ var n, k int fmt.Scan(&n, &k) var c []Customer for i := 0; i < n; i++ { var age int fmt.Scan(&age) if age >= 20 { c = append(c, &Adult{ Children: Children{TotalAmount: 0}, HasOrderedAlcohol: false, }) } else { c = append(c, &Children{TotalAmount: 0}) } } for i := 0; i < k; i++ { var s, amount int var o string fmt.Scan(&s, &o, &amount) if o == "alcohol" { c[s - 1].OrderAlCohol(amount) } else if o == "softdrink" { c[s - 1].OrderSoftdrink(amount) } else if o == "food" { c[s - 1].OrderFood(amount) } } for i := 0; i < n; i++ { fmt.Println(c[i].GetTotalAmount()) } } Goの場合継承が通じないのでインターフェースを定義することで解決しました。 ...