【发布时间】:2016-01-11 16:04:56
【问题描述】:
我想在 C# 中为 List 定义一些操作。 例如,加法 (+) 和转置 (')。 但是,当我编译代码时出现了错误。 我定义了一个继承自 List> 的矩阵类。 此外,我实现了 + 和 ' 运算符。 第一个很好,但是当我主要调用它时,会出现错误。 第二种方法甚至无法编译。 有人可以帮忙吗? 非常感谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Matrix : List<List<double>>
{
public static Matrix operator +(Matrix a, Matrix b)
{
Matrix c = new Matrix();
int i, j;
for (i = 0; i < a.Count; i++)
{
for (j = 0; j < a[1].Count; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
return c;
}
public static Matrix operator ' (Matrix a)
{
Matrix b = new Matrix();
int i, j;
for (i = 0; i<a.Count; i++)
{
for (j = 0; j < a[1].Count; j++)
{
b[j][i] = a[j][i];
}
}
return b;
}
public static int Main(string[] args)
{
Matrix x = new Matrix { new List<double> { 1, 2, 5, 2 }, new List<double> { 3, 4, 0, 7 } };
Matrix y = new Matrix { new List<double> { 1, 2, 5, 2 }, new List<double> { 3, 4, 0, 7 } };
Matrix z = new Matrix();
z = x + y;
Console.WriteLine(z);
return 0;
}
}
}
【问题讨论】:
-
您不能只选择“重载”您想要的任意符号。没有
'这样的运算符 -
您遇到什么错误?您遇到的具体问题是什么?
-
您没有为新矩阵 c 分配任何空间。
标签: c# matrix operator-keyword