无法应用operator / to operands struct和double

时间:2015-01-15 13:27:39

标签: c#

我遇到以下代码行的问题:

public Vector3 Normalized
{ get { return this / this.Length; } }

我收到错误:

  

“运算符”/'不能应用于Vector3类型的操作数   双“

为什么我收到此错误?

这是整个结构供参考:

struct Vector3
{
    public double x;
    public double y;
    public double z;

    public Vector3(double x, double y, double z)
        : this()
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public double X
    { get { return x; } set { x = value; } }

    public double Y
    { get { return y; } set { y = value; } }

    public double Z
    { get { return z; } set { z = value; } }

    public static Vector3 operator +(Vector3 vecA, Vector3 vecB)
    {
        return new Vector3(vecA.X + vecB.X, vecA.Y + vecB.Y, vecA.Z + vecB.Z);
    }

    public static Vector3 operator -(Vector3 vecA, Vector3 vecB)
    {
        return new Vector3(vecA.X - vecB.X, vecA.Y - vecB.Y, vecA.Z - vecB.Z);
    }

    public static Vector3 operator *(Vector3 vecA, Vector3 vecB)
    {
        return new Vector3(vecA.X * vecB.X, vecA.Y * vecB.Y, vecA.Z * vecB.Z);
    }

    public static Vector3 operator /(Vector3 vecA, Vector3 vecB)
    {
        return new Vector3(vecA.X / vecB.X, vecA.Y / vecB.Y, vecA.Z / vecB.Z);
    }

    public double Dot(Vector3 vec)
    {
        return (this.X * vec.X + this.Y * vec.Y + this.Z * vec.Z);
    }

    public static Vector3 Cross(Vector3 vecA, Vector3 vecB)
    {
        return new Vector3(vecA.Y * vecB.Z - vecA.Z * vecB.Y,
            vecA.Z * vecB.X - vecA.X * vecB.Z,
            vecA.X * vecB.Y - vecA.Y * vecB.X);
    }

    public double Length
    { get { return Math.Sqrt(X * X + Y * Y + Z * Z); } }

    public double LengthSq
    { get { return X * X + Y * Y + Z * Z; } }

    public Vector3 Normalized
    { get { return this / this.Length; } }
}

1 个答案:

答案 0 :(得分:11)

该结构没有将Vector3除以double的运算符。它应该是这样的:

public static Vector3 operator /(Vector3 vecA, double scalar)
{
    return new Vector3(vecA.X / scalar, vecA.Y / scalar, vecA.Z / scalar);
}