如何在数学对象等表达式中使用自定义类?

发布于 2024-07-27 20:17:08 字数 927 浏览 4 评论 0原文

我注意到可以定义一个自定义类,然后在其中一些上使用 +、-、/ 和 * 等运算符,而不是使用方法来执行此操作。 例如,我创建了一个执行复杂矩阵代数/微分的 Matrix 类,并创建了它,以便所有操作都由方法控制:

Matrix m1 = new Matrix(new double[][] { /* Some data */ });
Matrix m2 = new Matrix(new double[][] { /* Some other data */ });

// Returns a new Matrix object equal to the result
m1 = m1.Multiply(m2);
m1 = m1.Add(m2.Inverse);
m1 = m1.Subtract(m2.Determinant);
m1 = m1.ApplyToCombinator(new AlgebraMatrix(new string[][] { /* Some data *. }));

但是,在查看 此 CodeProject 页面,以及使用 XNA 框架后 (Position = Speed * (float)gameTime.ElapsedTime.TotalSeconds; 其中 a Vector2 对象正在使用 * 乘以 float),您可以使用 +、-、/ 和 * 代替。

那么我该如何更改我的类,以便我可以简单地键入以下代码来执行与上面相同的操作呢?

m1 = m1 * m2 + m2.Inverse - m2.Determinant;

提前致谢。

I have noticed that it is possible to define a custom class and then use operators like +,-,/ and * on a number of them rather than using methods to do so. For example, I created a Matrix class that does complex matrix algebra/differentiation and created it so that all the operations were controlled by methods:

Matrix m1 = new Matrix(new double[][] { /* Some data */ });
Matrix m2 = new Matrix(new double[][] { /* Some other data */ });

// Returns a new Matrix object equal to the result
m1 = m1.Multiply(m2);
m1 = m1.Add(m2.Inverse);
m1 = m1.Subtract(m2.Determinant);
m1 = m1.ApplyToCombinator(new AlgebraMatrix(new string[][] { /* Some data *. }));

However, after looking at This CodeProject Page, and after using the XNA framework (Position = Speed * (float)gameTime.ElapsedTime.TotalSeconds; where a Vector2 object is being multiplied by a float using *), you can use the +,-,/ and * instead.

So how would I have to change my class so I could simply type the following code to do the same as above?

m1 = m1 * m2 + m2.Inverse - m2.Determinant;

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

面犯桃花 2024-08-03 20:17:08

MSDN:运算符重载

public static Matrix operator +(Matrix mat)
{
    //do stuff  
}

MSDN: Operator overloading

public static Matrix operator +(Matrix mat)
{
    //do stuff  
}
风流物 2024-08-03 20:17:08

听起来您需要查看 运算符重载。 另请参阅本教程。 玩得开心 :)

Sounds like you need to look at Operator Overloading. Also see this tutorial. Have fun :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文