在我看来,这不仅仅是我的问题。
请不要重复关闭我的问题,因为我查看了这些问题但没有找到解决方案。
class Matrix<T> {
private Int32 rows;
private Int32 cols;
private T[,] matrix;
public Matrix() {
rows = cols = 0;
matrix = null;
}
public Matrix(Int32 m, Int32 n) {
rows = m;
cols = n;
matrix = new T[m, n];
}
public T this[Int32 i, Int32 j] {
get {
if (i < rows && j < cols)
return matrix[i, j];
else
throw new ArgumentOutOfRangeException();
}
protected set {
if (i < rows && j < cols)
matrix[i, j] = value;
else
throw new ArgumentOutOfRangeException();
}
}
public Int32 Rows {
get { return rows; }
}
public Int32 Cols {
get { return cols; }
}
public static Matrix<T> operator+(Matrix<T> a, Matrix<T> b) {
if(a.cols == b.cols && a.rows == b.rows) {
Matrix<T> result = new Matrix<T>(a.rows, a.cols);
for (Int32 i = 0; i < result.rows; ++i)
for (Int32 j = 0; j < result.cols; ++j)
result[i, j] = a[i, j] + b[i, j];
return result;
}
else
throw new ArgumentException("Matrixes don`t match operator+ requirements!");
}
public static Matrix<T> operator-(Matrix<T> a, Matrix<T> b) {
if (a.cols == b.cols && a.rows == b.rows) {
Matrix<T> result = new Matrix<T>(a.rows, a.cols);
for (Int32 i = 0; i < result.rows; ++i)
for (Int32 j = 0; j < result.cols; ++j)
result[i, j] = a[i, j] - b[i, j];
return result;
}
else
throw new ArgumentException("Matrixes don`t match operator- requirements!");
}
你知道编译器告诉了什么:“运算符'-'不能应用于'T'和'T'类型的操作数”,即适用于所有运算符。
那么,对此最好的决定是什么?据我所知,接口不能包含运算符,因此唯一的方法是 T 类型的抽象基类。而且,正如我发现的那样,不能将操作符定义为抽象的。