본문 바로가기
C#(CSharp)/기초강좌(Basic)

[16] C# 클래스 생성자, 파괴자, 스택틱 (C# class, constructor, destructor, static)

by swconsulting 2015. 2. 23.

클래스 객체 중요한 개념인 생성자, 파괴자, static에 대해서 알아 보겠습니다.


1) 생성자(Constructor), 파괴자(Destructor)


생성자와 파괴자는 클래스와 동일한 이름으로 만들어야 합니다. 파괴자에서는 앞에 ~ 키워드를 붙입니다.


생성자(Constructor) : class 객체로 생성되면서 호출 됩니다.

파괴자(Destructor) : class 객체에서 메모리로 돌아 가면서 파괴되면서 호출됩니다.


파괴자를 사용하는 가장 큰 이유는 위에서 언급한데로 객체를 더이상 사용하지 않는 경우에 호출 되기 때문에 리소스를 관리 할 수 있습니다. 즉, 메모리, File I/O등 컴퓨터의 리소스를 관리할 수 있습니다.


주의> 파괴자(Destructor)는 상속 또는 Overloaded 에서 자동으로 호출 되지 않습니다.

Destructors are not inheritable members, and are not virtual and so cannot be overridden. They always have the same signature so they cannot be overloaded.


<sample code>

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of a line
      public Line()  // constructor
      {
         Console.WriteLine("Object is being created");
      }
      ~Line() //destructor
      {
         Console.WriteLine("Object is being deleted");
      }

      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();
         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());           
      }
   }
}
Object is being created
Length of line : 6
Object is being deleted


메인 코드에서 line 객체를 new Line()으로 생성하면 바로 생성자가 호출이 됩니다. 이후 프로그램이 종료되면서

자동으로 line을 객체 파괴자가 호출 됩니다.


2) 클래스 Static

static 키워드 의미는 1개만 생성이 된다는 뜻입니다. 설명을 다시 하면 클래스 내부에 선언하면 클래스를 여러개 객체로 선언하더라도 내부에서는 1개만 생성이 됩니다.


2-1) static 변수(static variables)

using System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s1 = new StaticVar();
            StaticVar s2 = new StaticVar();
            s1.count();
            s1.count();
            s1.count();
            s2.count();
            s2.count();
            s2.count();         
            Console.WriteLine("Variable num for s1: {0}", s1.getNum());
            Console.WriteLine("Variable num for s2: {0}", s2.getNum());
            Console.ReadKey();
        }
    }
}
Variable num for s1: 6
Variable num for s2: 6


위 코드를 보면 s1, s2 각각 객체를 선언합니다. 하지만 StaticVar 클래스 내부에 num 멤버 변수는 공유를 합니다. 즉, s1, s2에서 각각 count() 함수를 호출하면 내부적으로 1개의 static 변수인 num값을 증가시킵니다.


2-2) static 함수(static functions)


using System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public static int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s = new StaticVar();
            s.count();
            s.count();
            s.count();                   
            Console.WriteLine("Variable num: {0}", StaticVar.getNum());
            Console.ReadKey();
        }
    }
}
Variable num: 3


함수를 클래스 내부에서 static 을 선언하고 사용하면 된다. 그리고 이 static 함수는 클래스에 선언한 static 변수만 접근이 가능합니다.

다른 일반 변수 (private, public, protected)는 접근이 가능하지 못합니다.


참고 : http://www.tutorialspoint.com/csharp/index.htm

'C#(CSharp) > 기초강좌(Basic)' 카테고리의 다른 글

[18] C# 다형성 (C# Polymorphism)  (0) 2015.02.23
[17] C# 상속 (C# Inheritance)  (0) 2015.02.23
[15] C# Enum  (0) 2015.02.23
[14] C# 문자열(C# String)  (0) 2015.02.23
[13] C# 배열 (C# Array and foreach)  (0) 2015.02.23