D 中的重载运算符

overloading operator in D

我正在尝试超载 + 但我遇到了错误:

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

此外,我的时间也出现了错误

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;
        }
    }
};
m2[i][j] = this[i][j] + b[i][j];

您必须定义 opIndex 才能使用这样的操作。例如:

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

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

或者就在该方法内部,您可能希望直接访问 double[][]

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

使用StopWatch。例如:

StopWatch sw;
sw.start();

// operations...

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