# "构造函数:有理数实例"相关问题

``````struct OurRational{T<:Integer} <: Real
num::T
den::T
function OurRational{T}(num::T, den::T) where T<:Integer
if num == 0 && den == 0
error("invalid rational: 0//0")
end
num = flipsign(num, den)
den = flipsign(den, den)
g = gcd(num, den)
num = div(num, g)
den = div(den, g)
new(num, den)
end
end
OurRational(n::T, d::T) where {T<:Integer} = OurRational{T}(n,d)
OurRational(n::Integer, d::Integer) = OurRational(promote(n,d)...)
OurRational(n::Integer) = OurRational(n,one(n))
⊘(n::Integer, d::Integer) = OurRational(n,d)
⊘(x::OurRational, y::Integer) = x.num ⊘ (x.den*y)
⊘(x::Integer, y::OurRational) = (x*y.den) ⊘ y.num
⊘(x::Complex, y::Real) = complex(real(x) ⊘ y, imag(x) ⊘ y)
⊘(x::Real, y::Complex) = (x*y') ⊘ real(y*y')
function ⊘(x::Complex, y::Complex)
xy = x*y'
yy = real(y*y')
complex(real(xy) ⊘ yy, imag(xy) ⊘ yy)
end
``````

``````z = (1 + 2im) ⊘ (1 - 2im)
``````

``````OurRational{Int64}(1, 2)ERROR: promotion of types OurRational{Int64} and
Int64 failed to change any arguments
``````

``````complex(real(x) ⊘ y, imag(x) ⊘ y)
``````

``````complex(1 ⊘ 2, 3 ⊘ 2)
``````

``````OurRational{Int64}(1, 2)ERROR: promotion of types OurRational{Int64} and
Int64 failed to change any arguments
``````

``````julia> complex(1//2, 3//2)
1//2 + 3//2*im
``````

``````//(x::Complex, y::Real) = complex(real(x)//y, imag(x)//y)
//(x::Number, y::Complex) = x*conj(y)//abs2(y)
``````

``````Base.complex(x::OurRational, y::OutRational) = 1.0 # change this to the right one!
z = (1 + 2im) ⊘ (1 - 2im) # return 1.0
``````

`complex`并不知道如何处理两个输入都是自定义的`OurRational`情况。

1 个赞

``````function complex(r::OurRational, im::OurRational)
complex(convert(Float64, r.num) / convert(Float64, r.den),
convert(Float64, im.num) / convert(Float64, im.den))
end
z = (1 + 2im) ⊘ (1 - 2im)# return -0.6 + 0.8im
``````