gpt4 book ai didi

java - 二元运算符的操作数类型错误 '+'

转载 作者:行者123 更新时间:2023-12-01 14:36:13 25 4
gpt4 key购买 nike

我正在创建一个通用类来操作矩阵。但问题是:当我实现加法运算时,我得到“二元运算符‘+’的操作数类型错误”

它说:

第一种类型:对象 第二种:T型 其中 T 是类型变量: T 扩展了 Matrix 类中声明的对象

有没有办法让它做加法?

这是我的代码:

public class Matrix<T> {
private T tab[][];
public Matrix( T tab[][])
{
this.tab = (T[][])new Object[tab.length][tab[0].length];
for(int i = 0; i < tab.length; i++){
System.arraycopy(tab[i], 0, this.tab[i], 0, tab.length);
}
}

public Matrix(int row, int column)
{
this.tab = (T[][])new Object[row][column];
}

//other constructors...

public Matrix addition(Matrix otherMatrix)
{
Matrix tmp = new Matrix(otherMatrix.getRowLen(), otherMatrix.getColLen());
for(int i = 0; i < tab.length; i++){
for(int j = 0; j < tab[0].length; j++){
//the line with the error is below
tmp.setElement(i, j, otherMatrix.getElement(i, j) + tab[i][j]);
}
}

return tmp;
}

public int getRowLen(){
return tab.length;
}

public int getColLen(){
return tab[0].length;
}

public void setElement(int i, int j, T value){
tab[i][j] = value;
}

public void setElement( T tab[][])
{
this.tab = (T[][])new Object[tab.length][tab[0].length];
for(int i = 0; i < tab.length; i++){
System.arraycopy(tab[i], 0, this.tab[i], 0, tab.length);
}
}

public T getElement(int i, int j){
return tab[i][j];
}
}

提前致谢!

最佳答案

Java 不支持对除基本数字类型和字符串 之外的任何内容使用+ 运算符。在这里,您不能在任意对象之间使用 + 运算符。

您在左侧得到了一个Object,因为otherMatrix 是一个原始(无类型)Matrix。右侧有一个 T,因为 tab 一般是用 T 定义的。

您无法在 Java 中重载运算符,因此您无法为任何 T 定义 +

您也许可以通过删除泛型并使用来获得您想要的东西

private int tab[][];

private double tab[][];

取决于您的需求。

关于java - 二元运算符的操作数类型错误 '+',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16466566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com