以下代码在go1.5验证通过

package main

import (
    "fmt"
)

type Person struct {
    name string
    age  int
    tel  string
}

type Student struct {
    Person // 有另一个字段
    school string
}

func (p *Person) Print() {
    fmt.Printf("Print\n")
    p.Hello() //指向person的hello
}

//在person上面定义了一个传值的method
func (p *Person) Hello() {
    p.tel = "186"
    fmt.Printf("Person My name is %s, and my tel number is %s\n", p.name, p.tel)
}

//多态
func (p *Student) Hello() {
    p.tel = "0117"
    fmt.Printf("student My name is %s, and my tel number is %s\n", p.name, p.tel)
}

func main() {
    anna := new(Student)
    anna.Person.name = "jim"
    anna.tel = "12345678"

    anna.Hello()  //student My name is jim, and my tel number is 0117
    anna.Person.Hello()  //Person My name is jim, and my tel number is 186
    anna.Print()  //Print
//Person My name is jim, and my tel number is 186 此处在c++会调用Student的Hello接口

}

 

相关文章:

  • 2022-12-23
  • 2022-02-02
  • 2022-12-23
  • 2021-08-11
  • 2022-12-23
  • 2021-09-28
  • 2022-12-23
猜你喜欢
  • 2022-02-06
  • 2021-11-28
  • 2021-09-17
  • 2022-12-23
  • 2021-06-21
相关资源
相似解决方案