zoukankan      html  css  js  c++  java
  • 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接口
    
    
    }

  • 相关阅读:
    元素定位方法与等待
    xpath定位的总结
    模拟登录
    shell的数组
    shell的函数
    shell的循环
    shell的流程控制语句case
    shell的while循环
    shell的if条件判断
    shell的for循环
  • 原文地址:https://www.cnblogs.com/chukuang2004/p/5112530.html
Copyright © 2011-2022 走看看