wad
wad

Reputation: 23

overloading operator in D

I am trying to overload + but I got the errors:

@Error1 Error: no [] operator overload for type main.Matrix

Besides, I also got errors for measuring the time.

import std.stdio;
import std.c.process;
import std.date;
//@Error2

class Matrix
{
    Matrix opBinary(string op)(Matrix another)
    {
        if(op == "+")
        {
            if (row != another.row || col != another.col)
            {
                // error
                getchar();
                return (this);
            }

            Matrix temp = new Matrix(row, col);

            for (int i = 0; i < row; i++)
                for (int j = 0; j < col; j++)
                    temp[i][j] = this[i][j] + another[i][j];
                    //@Error1

            return temp;
        }
    }
};

Upvotes: 2

Views: 98

Answers (1)

sigod
sigod

Reputation: 6486

m2[i][j] = this[i][j] + b[i][j];

You must define opIndex to use operations like this. E.g.:

double[] opIndex(size_t i1)
{
    return d[i1];
}

double opIndex(size_t i1, size_t i2)
{
    return d[i1][i2];
}

Or just inside of that method you might want to access double[][] directly:

m2.d[i][j] = this.d[i][j] + b.d[i][j];
std.date.d_time starttime = getCount();

Use StopWatch. E.g.:

StopWatch sw;
sw.start();

// operations...

sw.stop();
writefln("elapsed time = %s", sw.peek().msecs);

Upvotes: 1

Related Questions