Cha*_*hak 0 java copy-constructor
问题:
matrix m1 = new matrix(); // should produce a matrix of 3*3
matrix m2 = new matrix(5,4); //5*4
matrix m3 = new matrix(m2); //5*4
Run Code Online (Sandbox Code Playgroud)
在复制构造函数中应该有什么来制作与m2相同顺序的新矩阵m3?
public class matrix {
int a[ ][ ];
matrix(){
a = new int[3][3];
}
matrix(int x, int y){
a= new int [x][y];
}
matrix (matrix b1){
//how to use value of x and y here....
}
void show(){
System.out.println(a.length);
for(int i=0;i<a.length;i++){
System.out.print(a[i].length);
}
}
}
public class matrixtest {
public static void main(String [ ] args){
matrix a = new matrix();
matrix b = new matrix(5,4);
matrix c = new matrix (b);
a.show();
b.show();
c.show();
}
}
Run Code Online (Sandbox Code Playgroud)
注意:除数组a外,不能使用任何额外的实例变量.
接受的答案:@Chankey:this(b1.a.length,b1.a [0] .length); - 约翰
存储矩阵类中的行数和列数,并为它们创建getter.
public class Matrix {
int[][] a;
int rowNum;
int colNum;
//...
public Matrix(Matrix b) {
a=new int[b.getRowNum()][b.getColNum()];
this.rowNum = b.getRowNum();
this.colNum = b.getColNum();
}
public int getRowNum() {
return this.rowNum;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
762 次 |
| 最近记录: |