생성자와 인스턴스
Coddy의 C++ 개발자를 위한 C# 코스 레슨. 48개 중 33번째.
C++의 생성자와 비공개 상태는 익숙하지만, C#에서는 일반적인 변수 할당으로 클래스 인스턴스를 복사하는 것이 아니라 참조합니다. C#의 메모리 소유권은 스택 객체 및 수동 할당과 다르지만, 인스턴스별 불변 조건을 설계하는 것은 여전히 중요합니다.
생성자는 유효한 인스턴스를 만듭니다. 인스턴스 메서드는 this를 통해 해당 객체에서 동작하고, 필드는 호출 사이에 객체의 상태를 유지합니다. 업데이트할 때마다 값을 제한하는 것과 최종 합계만 제한하는 것은 다릅니다. 재사용 가능한 클래스를 연습 코드 및 실행기와 별도의 소스 파일에 작성하세요.
C++ 참고 코드
#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
class Counter { int count; public: explicit Counter(int n):count(max(0,n)) {} void add(int n) { count=max(0,count+n); } int value() const { return count; } };
int main() {
Counter counter(1); counter.add(3); cout << counter.value() << "\n";
}
C# 보조 선언
class NamedItem { public string Name { get; private set; } public NamedItem(string name) { Name = name; } }Main 내부의 C# 문장
var item = new NamedItem("pen");
Console.WriteLine(item.Name);이 내용은 핵심 개념을 가르치기 위한 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장을 보여 줍니다.
참고 출력:
4C# 출력:
pen챌린지
쉬움Counter.cs에서 Counter를 완성하세요. 초기값을 max(0, initial)로 설정하세요. 변경 사항을 한 번에 하나씩 적용하고, 각 덧셈 후 상태가 0보다 작아지지 않도록 제한하세요. Value를 노출하세요. 서로 다른 인스턴스는 상태를 공유하면 안 됩니다.
잠금 해제된 C# 파일을 수정하세요. 화면에 표시된 잠긴 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하고, 입력이 변경되지 않았는지 확인한 다음 마지막에 줄바꿈 하나를 붙여 결과를 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 출력하지 마세요.
잠긴 실행기도 Solve 래퍼뿐만 아니라 내보낸 도우미 또는 클래스 API를 독립적으로 검사합니다.
직접 해보기
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = Ints(input[1]); string before1=Snapshot(a1);
var c1 = new Counter(1); var c2 = new Counter(7); c1.Add(-5); c1.Add(2); if (c1.Value != 2 || c2.Value != 7 || new Counter(-1).Value != 0) throw new Exception("Counter API");
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러