【发布时间】:2020-03-26 11:31:57
【问题描述】:
我想在一个类中有两个构造函数,但我不能。我知道这是可能的,但我找不到我的错误。
public static class Matrix{
int [][] matrix;
int row;
int column;
String matrixName;
Matrix (String [] input, String name) {
matrixName = name;
column = input.length;
row = input[0].split(",").length;
matrix = new int [row][column];
initialize(input);
}
Matrix (Matrix A, char ch) {
if (ch == 'T'){
column = A.row;
row = A.column;
}
else{
column = A.column;
row = A.row;
}
matrix = new int[row][column];
matrixName = "result";
}
第二个矩阵不能定义为构造函数。
【问题讨论】:
-
您遇到了什么错误?
-
@AbhiN 在另一个类中我有
Matrix result = new Matrix (Matrix A, 'R');并且我收到此错误 Error:(121, 47) java: ')' expected Error:(121, 48) java: not a statement 错误: (121, 49) java: ';'预计 -
只写
A作为new调用中的第一个参数,而不是Matix A。 -
我认为您不能将 Matrix 作为参数传递,因为如果允许,那么对于该 Matrix A 对象的初始化,将需要执行第二个构造函数,您可以使用第二个构造函数来执行它并且在该执行中,第二个构造函数也需要再次执行,这样你就会陷入无限循环。
-
投反对票,因为您没有分享错误消息。见minimal reproducible example,谢谢。
标签: java class constructor