从下面的例子来看,Child 对象是否可以调用Parent 的方法?例如,我想让 child (男孩 1 和女孩 1)调用 parent 的“记住”方法;这样 parent 就可以记住 child 想让他们记住的东西。
非常感谢
package main
import "fmt"
type child struct {
Name string
}
func (p *child) Yell() {
fmt.Println("Child's yelling")
}
type parent struct {
Name string
Children []child
Memory []string
}
func (p *parent) Yell() {
fmt.Println("Parent's yelling")
}
func (p *parent) Remember(line string) {
p.Memory = append(p.Memory, line)
}
func main() {
p := parent{}
p.Name = "Jon"
boy1 := child{}
boy1.Name = "Jon's boy"
girl1 := child{}
girl1.Name = "Jon's girl"
p.Children = append(p.Children, boy1)
p.Children = append(p.Children, girl1)
fmt.Println(p)
p.Yell()
for i:=0;i<len(p.Children);i++ {
p.Children[i].Yell()
}
}
感谢@Jim,这是解决方案。指针总是令人困惑。
主要包
import "fmt"
type child struct {
Name string
prnt *parent
}
func (p *child) Yell() {
fmt.Println("Child's yelling")
}
type parent struct {
Name string
Children []child
Memory []string
}
func (p *parent) Yell() {
fmt.Println("Parent's yelling")
}
func (p *parent) Remember(line string) {
p.Memory = append(p.Memory, line)
}
func main() {
p := parent{}
p.Name = "Jon"
boy1 := child{}
boy1.Name = "Jon's boy"
boy1.prnt = &p
girl1 := child{}
girl1.Name = "Jon's girl"
girl1.prnt = &p
p.Children = append(p.Children, boy1)
p.Children = append(p.Children, girl1)
fmt.Println(p)
p.Yell()
for i := 0; i < len(p.Children); i++ {
p.Children[i].Yell()
p.Children[i].prnt.Remember("test:" + p.Children[i].Name)
}
fmt.Println(p.Memory)
}
最佳答案
您可以在子结构中添加指向父结构的指针
type child struct {
Name string
parent *parent
}
func (p *child) Yell() {
fmt.Println("Child's yelling")
p.parent.Remember(p.Name + " called")
p.parent.Yell()
}
关于oop - Golang,调用 parent 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35804991/