GO语言使用之面向对象编程(9)面向对象编程应用

一、面向对象编程的步骤

1、声明(定义)结构体,确定结构体名
2、编写结构体的字段
3、 编写结构体的方法

二、实现案例:

1) 编写一个Student结构体,包含name、gender、age、id、score字段,分别为string、string、int、int、float64类型。
2) 结构体中声明一个say方法,返回string类型,方法返回信息中包含所有字段值。
3) 在main方法中,创建Student结构体实例(变量),并访问say方法,并将调用结果打印输出。

type person struct{
    Name string
    Age int
}

func (p person) showInforn()  {
    fmt.Printf("name=%s age=%d\n",p.Name,p.Age)
}

func (p person) speak()  {
    fmt.Printf("%s 是一个好人\n",p.Name)
}

func (p person) jisuan()  {
    sum := 0
    for i := 1; i < 101; i++ {
           sum += i
    }
    fmt.Printf("1+~+100的和为%d \n",sum)
}

func (p person) jisuan2(n int) (sum int) {

    for i := 1; i <= n; i++ {
           sum += i
    }
    fmt.Printf("1+~+%d的和为%d \n",n,sum)
    return
}

func (p *person) pointDemo() {
    p.Name="Tom"
    p.Age=100
}
func StructMethodDemo()  {
    p :=person{"张三",18}
    p.showInforn()
    p.speak()
    p.jisuan()
    res :=p.jisuan2(1000)
    fmt.Printf("返回值为 %d \n",res)
    p1 :=&person{"张三",18}
    fmt.Println("------------------------")
    fmt.Printf("指针调用前返回值p= %v \n",*p1)
    p1.pointDemo()//标准调用
    fmt.Printf("指针调用后返回值p= %v \n",*p1)

}

猜你喜欢

转载自blog.csdn.net/TDCQZD/article/details/81712860