如何在数学对象等表达式中使用自定义类?
我注意到可以定义一个自定义类,然后在其中一些上使用 +、-、/ 和 * 等运算符,而不是使用方法来执行此操作。 例如,我创建了一个执行复杂矩阵代数/微分的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MSDN:运算符重载
MSDN: Operator overloading
听起来您需要查看 运算符重载。 另请参阅本教程。 玩得开心 :)
Sounds like you need to look at Operator Overloading. Also see this tutorial. Have fun :)