C# 강좌 : 제 35강 - 중첩 생성자
중첩 생성자(Overloaded Constructor)
클래스에서 new 키워드를 사용하여 개체를 만들 때, 인스턴스 멤버 변수를 생성하고 초기화 하는데 사용합니다.
중첩 생성자는 생성자를 오버로드 (Overload) 시켜 다양한 인스턴스 멤버 변수에 대해 대응할 수 있습니다.
클래스가 생성될 때 마다 인수에 맞는 인스턴스 생성자
를 호출하여 해당 인수를 필드의 값으로 초기화합니다.
중첩 생성자 생성
using System;
class Position
{
private int X, Y = 0;
public Position(int x, int y)
{
this.X = x;
this.Y = y;
}
public Position(double x, double y)
{
this.X = (int)x;
this.Y = (int)y;
}
public string Location()
{
return $"({X}, {Y})";
}
}
이름이 중복되는 Position
생성자를 정의하여 서로 다른 매개 변수를 인수로 받아 들어오는 형태에 따라 맞는 생성자로 진행하게 됩니다.
생성자가 2 개 이상이여도 하나의 생성자만 호출합니다.
매개 변수의 개수는 일치될 필요가 없으며, 서로 다른 데이터 형식을 사용할 수 있습니다.
중첩 생성자 접근
Position position1 = new Position(2, 1);
Console.WriteLine(position1.Location());
Position position2 = new Position(3.5, 2.0);
Console.WriteLine(position2.Location());
int
형식의 값을 사용할 경우, 첫 번째 생성자로 사용됩니다.
double
형식의 값을 사용할 경우, 두 번째 생성자로 사용됩니다.
공유하기


댓글 남기기