D中的重载运算符
我正试图过载D中的重载运算符,d,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 == "+
+
,但出现了以下错误:
@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;
}
}
};
导入标准stdio;
进口标准c工艺;
进口标准日期;
//@错误2
类矩阵
{
矩阵opBinary(字符串op)(矩阵另一个)
{
如果(op==“+”)
{
if(row!=另一个.row | | col!=另一个.col)
{
//错误
getchar();
返回(本);
}
矩阵温度=新矩阵(行、列);
对于(int i=0;i|
必须定义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在几年前被删除,替换为std.datetime,并且您还没有尝试使用它来重载索引操作符。您是否打算亲自访问双阵列?是的。如何更改阵列的数据?我不知道如何重载索引运算符protip:将
if(op==“+”)
等替换为static if(op==“+”)
,因为op
是一个模板参数,在编译时是已知的。谢谢,但是static if会给我同样的错误。
m2.d[i][j] = this.d[i][j] + b.d[i][j];
std.date.d_time starttime = getCount();
StopWatch sw;
sw.start();
// operations...
sw.stop();
writefln("elapsed time = %s", sw.peek().msecs);