zl程序教程

您现在的位置是:首页 >  后端

当前栏目

go语言面向对象之方法详解编程语言

Go方法语言编程语言 详解 面向对象
2023-06-13 09:11:54 时间
//在面向对象编程中,一个对象其实就是一个简单的值或者一个变量,在这个 //对象中包含一些函数 //这种带有接受者的函数,我们称之为方法,本质上,一个方法 //则是一个和特殊类型关联的函数
//面向对象的方式定义方法,这个意思是AddOOP这个方法是属于a这个类型的。方法和函数的不同就是方法有一个接受者,这里的接受者就是a这个类型 //这里必须要是自定义类型,比如这里就不能使用int,可以是指针类型和非指针类型
//可以为基础类型添加方法,也可以为结构体类型添加方法,下面的例子就是为基础类型添加方法 func (a myint)AddOOP(b myint) myint{ return a + b

如果指针类型作为方法的接受者,在方法内部修改这个对象,是修改的一份数据,对外部的结构体是有影响的

如果是一个结构体作为方法的接受者,在方法内部修改这个对象,是修改的另外一份数据,对外部的结构体是没有影响的

3、实现继承和重写

package main 


//为Student31这个结构体定义方法,如果父类有一个相同的方法,则相当于重写父类的方法 func (p *Student31) PrintValue3() { fmt.Printf("%s,%c,%d/n",p.name,p.sex,p.age) fmt.Printf("%d,%s/n",p.id,p.addr)
p2 := Student31{Person2:Person2{"ddd",12,f},id:10,addr:"dddddddddd"} //子类调用父类的方法 ( p2).PrintValue2() //ddd,f,12 //子类调用重写的方法 ( p2).PrintValue3() //ddd,f,12 //10,dddddddddd //如果子类和父类有相同的方法,如果一定要调用父类的方法,则用下面的方式来调用 //p2.Person2.PrintValue2()

4、调用方法的三种方法

package main 

import "fmt" 

type Person3 struct { 

 name string 

 age int 

 sex byte 

func (p *Person3)Test1() { 

 //%p表示地址,%v表示值 

 fmt.Printf("%p,%v",p,p) 

func main() { 

 p1 := Person3{name:"abc",age:12,sex:a} 

 //传统的调用方法 

 ( p1).Test1() 

 //0x1f4400d0, {abc 12 97 


//test11_1这个方法属于一个指针变量,而这个指针变量必须指向P1这个结构体 func (p *P1)test11_1(n int) { p.oop3 += n fmt.Println(p)
//test11_1这个方法属于一个结构体,而这个结构体必须是P1这个结构体的实例 //func (p P1)test11_1(n int) { // p.oop3 += n // fmt.Println(p)
test11_2 := P1{oop1:"oop1",oop2:"oop2",oop3:3} //test11_2 := P1{oop1:"oop1",oop2:"oop2",oop3:3}
test11_3 := P1_1{P1:P1{oop1:"oop1_oop1",oop2:"oop2_oop2",oop3:4},oop4:"oop4_oop4",oop5:"oop5_oop5",oop6:m} //test11_3 := P1_1{P1:P1{oop1:"oop1_oop1",oop2:"oop2_oop2",oop3:4},oop4:"oop4_oop4",oop5:"oop5_oop5",oop6:m} test11_2.test11_1(2) fmt.Println(test11_2) //如果父类和子类有相同的方法,那么子类去调用这个方法,则默认会调用子类的方法 //test11_3.test11_1(3) //fmt.Println(test11_3)
//如果父类和子类有相同的方法,通过下面的方法可以去调用父类的方法 test11_3.P1.test11_1(3) fmt.Println(test11_3)

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/20925.html

cgo