Menu
CoddyTech

암묵적 인터페이스

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

C에는 interface 키워드가 없습니다. 계약은 보통 각 구현이 채워 넣는 함수 포인터로 이루어진 struct이며, 컴파일러는 각 함수의 형식이 해당 멤버와 일치하는지만 확인하고 어떤 타입이 무언가를 구현하겠다고 약속했는지는 확인하지 않습니다. 모든 일반 Dart 클래스는 인스턴스 멤버로부터 암시적 인터페이스를 정의하며, 여기에는 해당 라이브러리 안에서만 보이는 private 멤버도 포함됩니다. implements는 본문을 상속하지 않고 계약을 제공합니다. Dart의 하위 타입 관계는 명목적입니다.

모든 일반 Dart 클래스는 인스턴스 멤버로부터 암시적 인터페이스를 정의합니다. private 멤버는 해당 인터페이스에 포함되지만, 라이브러리 내부에서만 볼 수 있습니다. implements는 구현 본문을 상속하지 않고 명목적 계약을 설정합니다.

완전한 C 프로그램:

#include <stdio.h>

struct sound {
    const char *(*sound)(void);
};

static const char *bell_sound(void) { return "ding"; }

static const struct sound bell = {bell_sound};

int main(void) {
    const struct sound *s = &bell;
    printf("%s\n", s->sound());
    return 0;
}

완전한 Dart 프로그램:

abstract class Sound{String sound();}
class Bell implements Sound{String sound()=>'ding';}
void main(){Sound s=Bell();print(s.sound());}
challenge icon

챌린지

쉬움

추상 Scorer를 구현하고 int score(String text)를 작성하세요. LengthScore implements Scorer는 ASCII 문자열의 길이를 반환합니다. VowelScore implements Scorer는 소문자 a,e,i,o,u만 셉니다. functions.dart의 best(List<String> words,Scorer scorer)는 점수가 가장 높은 첫 번째 단어를 반환하며, 비어 있으면 null을 반환합니다. 입력은 length 또는 vowels로 시작한 뒤 ASCII 단어가 이어집니다. 출력은 가장 좋은 단어 또는 none입니다.

편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart가 입력을 분석하고 출력을 반환하며, 잠긴 드라이버는 공개 API를 독립적으로 테스트한 뒤 결과를 줄바꿈 하나와 함께 출력합니다.

코드는 Scorer.dart, LengthScore.dart, VowelScore.dart, functions.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.

직접 해보기

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Scorer.dart';
import 'LengthScore.dart';
import 'VowelScore.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(LengthScore().score('abc')==3 && VowelScore().score('area')==3);check(best(['x','aaa'],LengthScore())=='aaa');
stdout.writeln(solve(input));
}
quiz icon실력 점검

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

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

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