티스토리 뷰

static 함수에서 일반 멤버변수 사용하기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Date mydate = new Date();
            Console.WriteLine(mydate.DayOfYear());
        }
    }
 
    class Date
    {
        public int year;
        public int month;
        public int day;
        public static bool IsLeapYear(int year)
        {
            return (year % 4 == 0&& ((year % 100 != 0|| (year % 400 == 0));
        }
        public int DayOfYear()
        {
            int[] MonthDays = new int[] { 0315990 };
            return MonthDays[month - 1+ day;
        }
    }
}
cs

8행에서 DayOfYear() 를 호출할때 DayOfYear()가 static 함수가 아니므로 클래스명인 Date가 아닌 객체명인 mydate 가 와야 한다.

static 멤버함수는 static (멤버)변수와 static 멤버함수만 참조할 수 있다.

17행에서 IsLeapYear는static 함수라서 year 변수를 강제로 전달해줘야만 사용 가능하다.
만약, year가 static 변수라면 전달하지 않고도 사용 가능하다.

21행에서 DayOfYear() 는 static 함수가 아니므로 day 변수를 전달하지 않고도 그냥 사용 가능하다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28