Menu
CoddyTech

추상 클래스

Coddy의 C 개발자를 위한 C# 코스 레슨. 48개 중 39번째.

C에는 추상 클래스가 없습니다. 도형 계약은 함수 포인터가 있는 구조체이며, 코드에서 struct Shape를 선언하고 area 포인터를 NULL로 설정해도 이를 막을 수 있는 것은 없습니다. 이를 호출하면 정의되지 않은 동작이 발생합니다. C# 추상 클래스는 new로 생성할 수 없고, 추상 메서드에는 본문이 없으며, 이를 재정의하는 것을 잊은 구체 클래스는 컴파일러가 거부합니다. 가비지 수집기가 객체를 회수하므로, 기반 포인터를 통한 free를 제대로 처리할 필요가 없습니다.

추상 클래스는 공통 구조를 정의하고 파생 클래스가 동작을 구현하도록 요구할 수 있습니다. 추상 클래스는 직접 인스턴스화할 수 없습니다. 기반 클래스의 추상 메서드에는 본문이 없으며 파생된 구체 클래스는 이를 재정의해야 합니다. 다형성 컬렉션을 사용하면 호출자가 구체 클래스 유형을 일일이 검사하지 않고도 넓이를 요청할 수 있습니다.

C 참조

#include <stdio.h>

struct Shape {
    double (*area)(const struct Shape *self);
};

struct Triangle {
    struct Shape shape;   /* 첫 번째 멤버이므로 Triangle을 Shape으로 사용할 수 있음 */
    int b, h;
};

static double triangle_area(const struct Shape *self) {
    const struct Triangle *t = (const struct Triangle *)self;
    return t->b * t->h / 2.0;
}

int main(void) {
    struct Triangle triangle = { { triangle_area }, 3, 2 };
    struct Shape *shape = &triangle.shape;
    printf("%.1f\n", shape->area(shape));
    return 0;
}

C# 지원 선언

abstract class Named { public abstract string Describe(); }
class NamedCode : Named { private string code; public NamedCode(string code) { this.code = code; } public override string Describe() { return "code:" + code; } }

Main 내부의 C# 문장

Named item = new NamedCode("A");
Console.WriteLine(item.Describe());

이 내용은 핵심을 짚어 설명하기 위한 발췌문입니다. 챌린지 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 스니펫은 관련 선언과 문장만 보여 줍니다.

참조 출력:

3.0

C# 출력:

code:A
challenge icon

챌린지

쉬움

추상 클래스 Shape를 상속하는 Rectangle과 Triangle을 구현하세요. Rectangle의 넓이는 width * height입니다. Triangle의 넓이는 base * altitude / 2.0입니다. Shape 참조를 통해 두 넓이의 합을 반환하세요. 각 변의 길이는 0 이상의 정수입니다.

잠금 해제된 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 = I(input[1]); string before1=Snapshot(a1);
var a2 = I(input[2]); string before2=Snapshot(a2);
var a3 = I(input[3]); string before3=Snapshot(a3);
Shape sh1 = new Rectangle(2,3); Shape sh2 = new Triangle(1,1); if (sh1.Area() != 6 || sh2.Area() != 0.5) throw new Exception("Shape API");
var result = Exercise.Solve(a0,a1,a2,a3);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
if (Snapshot(a2) != before2) throw new Exception("Input mutation");
if (Snapshot(a3) != before3) throw new Exception("Input mutation");
Console.WriteLine(result.ToString("0.0", CultureInfo.InvariantCulture));
}
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C 개발자를 위한 C#의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러