Reputation: 1976
I'm writing a small console app. I have no idea what's wrong...
namespace Mtrx
{
class Mtrx
{
private double[,] _sqMtrx;
private double _mtrxSize { get; set; }
public Mtrx(int i)
{
if (i <= 0)
throw new FormatException();
else
this._sqMtrx = new double[i, i];
_mtrxSize = i;
}
public static Mtrx operator +(Mtrx m1, Mtrx m2)
{
if (m1._mtrxSize == m2._mtrxSize)
{
for (int i = 1; i <= m1._mtrxSize; i++)
{
for (int j = 1; j <= m1._mtrxSize; j++)
{
return m1[i, j] == m1[i, j] + m2[i, j];
}
}
}
}
}
}
and I get: Cannot apply indexing with [] to an expression of type 'Mtrx.Mtrx'
Upvotes: 0
Views: 962
Reputation: 146469
Shouldn't the innermost line in your nested for loops be referencing the array, not the mr1, mr2 variables?
public static Mtrx operator +(Mtrx m1, Mtrx m2)
{
if (m1._mtrxSize == m2._mtrxSize)
{
var outVal = new Mtrx(m1._mtrxSize)
for (int i = 1; i <= m1._mtrxSize; i++)
for (int j = 1; j <= m1._mtrxSize; j++)
outVal._sqMtrx[i,j] = m1._sqMtrx[i, j] + m2._sqMtrx[i, j];
return outVal;
}
}
If you want to use indexing syntax on the class itself, then you must add an indexer....
class Mtrx
{
private double[,] _sqMtrx;
private int _mtrxSize { get; set; }
public Mtrx(int i)
{
if (i <= 0)
throw new FormatException();
else
this._sqMtrx = new double[i, i];
_mtrxSize = i;
}
public double this[int i, int j]
{
get { return _sqMtrx[i, j]; }
set { _sqMtrx[i, j] = value; }
}
public static Mtrx operator +(Mtrx m1, Mtrx m2)
{
if (m1._mtrxSize == m2._mtrxSize)
{
var outVal = new Mtrx(m1._mtrxSize)
for (int i = 1; i <= m1._mtrxSize; i++)
for (int j = 1; j <= m1._mtrxSize; j++)
outVal[i,j] = m1[i, j] + m2[i, j];
return outVal;
}
}
}
Upvotes: 1
Reputation: 1332
You are trying to access your object like an array, instead of accessing array inside your object. try m1._sqMatrix[i,j]
Upvotes: 2
Reputation: 1500165
Well yes, the problem is here:
return m1[i, j] == m1[i, j] + m2[i, j];
This is wrong in all kinds of ways:
bool
when the operator is meant to return a Mtrx
(horrible name, by the way - embrace vowels!)You're trying to use an indexer on m1
and m2
, which are variables of type Mtrx
. You haven't created an indexer. You either need to use m1._sqMtrx[i, j]
etc, or you need to declare an indexer, such as:
public double this[int i, int j]
{
return _sqMtrx[i, j];
}
Your method doesn't return anything if the two arguments have different sizes
Fundamentally I think you should think again about the whole operator.
Upvotes: 8