2014-09-26 63 views
2
  1. 如何實現「虛擬繼承」?什麼是go lang的虛擬繼承?

  2. go lang編譯器版本:「1.3.1 windows/amd64」,是否支持「虛擬繼承」

我從來沒有聽說過C語言可以支持「虛擬」,所以我真的很誤解。

+0

是,在C概念++。但我從別人那去支持它聽到。我以前從來沒有聽說過它。@ nos – 2014-09-26 11:21:12

+0

男孩,它很複雜。你可以用[類型嵌入](http://golang.org/ref/spec#Struct_types)(查找「匿名類型」)和[接口](http:/ /golang.org/ref/spec#Interface_types)或其組合。 – twotwotwo 2014-09-26 19:31:26

回答

9

Virtual Inheritance解決方案a problem如果您沒有多重繼承,則不存在它不存在。考慮下面的繼承樹:

A 
/\ 
B C 
\/
    D 

如果類B和C都提供了一個數據成員(或爲此事法)使用相同的名字,那麼當訪問所述成員d,你需要一種方法來消除歧義,其祖先的數據成員(或方法),你想訪問。

虛擬繼承是C++的解決方案。

在你沒有繼承開始;只有組成,你可以一次嵌入任何給定類型的最多1個成員。

http://play.golang.org/p/1iYzdoFqIC

package main 

type B struct { 
} 

func (b B) Foo() {} 

type C struct { 
} 

func (c C) Foo() {} 

type D struct { 
    B 
    C 
} 

func main() { 
    d := D{B{}, C{}} 
    // d.Foo() // <- ambiguous 
    d.B.Foo() // <- ok 
    d.C.Foo() // <- ok 
} 
+0

現在我對「繼承」和「虛擬繼承」這個概念有了更好的理解。和我一樣,非常感謝。 – 2014-09-27 08:25:31

+0

正是......並且這個問題僅與[名義子分類](https://en.wikipedia.org/wiki/Nominal_type_system)的語言相關。 Go不是OO語言,因此虛擬繼承意圖解決的問題是不相關的。 – 2018-01-07 07:00:08

0

「虛繼承」 更多的東西像這樣

http://play.golang.org/p/8RvPmB3Pof

package main 

type A struct { 
    virtual int 
} 

func (a *A) set(v int) { 
    a.virtual = v 
} 

func (a *A) get() int { 
    return a.virtual 
} 

type B struct { 
    *A 
} 

type C struct { 
    *A 
} 

type D struct { 
    *B 
    *C 
} 

func main() { 
    a := &A{} 
    b := &B{a} 
    c := &C{a} 
    d := &D{b, c} 
    d.B.set(3) 
    println(d.C.get()) 
    return 
}