로그인 :
이 코드의 목적은 무엇인가?
public Fraction(Fraction other) {
num = other.num;
denom = other.denom;
}
이 같은 생성자가있는 경우 :
public Fraction(int n, int d) {
num = n;
denom = d;
}
왜 초기화해야합니까 other.num
에 num
와 other.denom
에 denom
. 복사 생성자의 구문을 무엇입니까? 목적은 무엇인가?
레오 아소 :
당신은 단순히 입력한다면
public Fraction(Fraction other) {
}
자바는 단순히 당신의 값을 복사 할 것을 생각하지 않을 other
새 개체로. 자바는 자동으로 그렇게 당신을 위해 당신의 변수를 초기화하지 않습니다. 이 복사 생성자로 들어, 당신은 여전히 수동에서 복사 필드라는 코드 밖으로 입력 할 필요가 other
개체에 당신이 생성됩니다. 이 같이 :
public Fraction(Fraction other) {
num = other.num;
denom = other.denom;
}
생성자는 새로운를 생성 Fraction
하지만, 당신이 수동으로 수행하는 그 안에 입력 코드입니다 그것을 "복사 생성자"하게하고 당신이 할 수 있다는 것 "복사"
Fraction a = Fraction(4, 20);
Fraction b = new Fraction(a);
// b has the same values as a but is a different object
이미 다른 생성자가있는 경우 물론, 짧은 방법은 복사 생성자가 만들
public Fraction(int n, int d) {
num = n;
denom = d;
}
public Fraction(Fraction other) {
this(other.num, other.denom);
}