golang 多态和c++的一点区别

以下代码在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接口

}

 

posted @ 2016-01-08 11:15  chukuang2004  阅读(646)  评论(0编辑  收藏  举报