class Item
{
public int price;
public Item()
{
price = 1000;
Console.WriteLine("Create Item");
}
}
메인 함수에서 객체 생성

item1 & item2 객체가 서로 같은 주소를 가리키는중
같은 메모리 공간을 참조 하고 있기 때문에 하나의 객체로 값을 변경하면 서로 참조된 객체도 함께 영향 ㅇ
-> ✅ 따라서 item2의 값을 변경하면 참조된 또다른 객체인 item1도 영향ㅇ
static void Main(string[] args)
{
Item item1 = new Item();
Item item2 = item1;
item2.price = 999;
Console.WriteLine("item1의 price 값: " + item1.price);
Console.WriteLine("item2의 price 값: " + item2.price);
}
결과값 :

ex) Unit 클래스 생성
class Unit
{
public int health;
public int attack;
public int[] score;
public Unit() // 생성자
{
Console.WriteLine("생성자");
score = new int[3];
}
public Unit(Unit clone) // 복사생성자 -> 매개변수로 Unit이 들어옴
{
Console.WriteLine("복사 생성자");
// 개별적인 새로운 인스턴스
score = new int[3];
health = clone.health;
attack = clone.attack;
}
}
메인 함수
Unit marine1 = new Unit();
marine1.health = 100;
marine1.attack = 10;
marine1.score[0] = 5;
marine1.score[1] = 10;
marine1.score[2] = 15;
// 복사 생성자
Unit marine2 = new Unit(marine1);
marine2.score[0] = 3;
marine2.score[1] = 3;
marine2.score[2] = 3;
for(int i = 0; i < marine1.score.Length; i++)
{
Console.WriteLine("marine1의 score [" + i + "] :" + marine1.score[i]);
}
for (int i = 0; i < marine2.score.Length; i++)
{
Console.WriteLine("marine2의 score [" + i + "] :" + marine2.score[i]);
}
결과값 :