VB.net的Friend
以前学过一点C++
所以对VB.NET中的friend感到很困惑,老是以为类中的友元过程其表现应该和C++一样,所以我在写个简单的程序中(一个有理数类):
Public Class Fraction
#Region "Data Fields"
Private numerator As Integer '分子
Private denominator As Integer '分母
#End Region
#Region "Methods"
Friend Function Add(ByVal f1 As Fraction, ByVal f2 As Fraction) As Fraction
'友元函数,加法为二元运算符,想做成Add(f1,f2)这样求两个分数的和
Dim t1 As Integer
Dim f As New Fraction
t1 = lcm(f1.denomIs(), f2.denomIs())
'numerator = numerator * (t1 / denominator) + frac1.numIs() * (t1 / frac1.denomIs())
f.numerator = f1.numerator * (t1 / f1.denominator) + f2.numerator * (t1 / f2.denominator)
f.denominator = t1
Return f
End Function
Public Function Subtract(ByVal frac1 As Fraction) As Fraction
End Function
Public Function Mult(ByVal frac1 As Fraction) As Fraction
End Function
Public Function numIs() As Integer '返回分子
Return numerator
End Function
Public Function denomIs() As Integer '返回分母
Return denominator
End Function
Public Sub New()
End Sub
Public Sub New(ByVal num As Integer, ByVal denom As Integer)
Dim t1 As Integer
t1 = gcd(num, denom)
num /= t1
denom /= t1
numerator = num
denominator = denom
End Sub
Private Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer '最大公约数
Dim c As Integer
If a < b Then
c = a
a = b
b = c
End If
c = a Mod b
While (c <> 0)
a = b
b = c
c = a Mod b
End While
Return b
End Function
Private Function lcm(ByVal a As Integer, ByVal b As Integer) As Integer '最小公倍数
Dim c As Integer
If a < b Then
c = a
a = b
b = c
End If
c = a
Do While (c Mod b <> 0)
c = c + a
Loop
Return c
End Function
Public Sub Print()
Console.WriteLine(numerator & "/" & denominator)
End Sub
#End Region
End Class
可是我想在模块中:
Module Module1
Sub Main()
Dim a As Fraction = New Fraction(1, 2)
Dim b As New Fraction(1, 3)
Dim c As New Fraction
a.Print()
b.Print()
c = Add(a, b) '<-------------这里无法调用
c.Print()
Console.Read()
End Sub
End Module
想问的是,friend在vb.net中跟c++中的到底有什么不同?
能不能实现二元加Add?
[解决办法]
Imports NameSpaces.Fraction
加了以后可以直接用这个Fraction类的静态方法