클래스와 인스턴스
Coddy의 GDScript 개발자를 위한 Dart 코스 레슨. 48개 중 27번째.
GDScript와 Dart의 인스턴스 멤버는 클래스 안에 선언되며, 메서드는 명시적인 수신자 매개변수 없이도 멤버에 접근할 수 있습니다. GDScript는 .new()로 스크립트 인스턴스를 만들고, Dart는 new를 요구하지 않고 클래스 생성자를 호출합니다. 아래에서 독립적으로 생성된 각 Lamp는 자체 on 필드를 가집니다.
클래스 안에 필드와 메서드를 선언하고 new를 요구하지 않고 인스턴스를 생성하세요. 각 인스턴스에는 자체 인스턴스 필드가 있습니다. 코스 과제에서는 각 필수 타입을 이름이 지정된 별도의 라이브러리 파일에 배치합니다.
완성된 GDScript 프로그램:
extends Node
class Lamp:
var on := false
func toggle() -> void:
on = not on
func _ready() -> void:
var a = Lamp.new()
var b = Lamp.new()
a.toggle()
print("%s:%s" % [a.on, b.on])
완성된 Dart 프로그램:
class Lamp{bool on=false;void toggle(){on=!on;}}
void main(){final a=Lamp(),b=Lamp();a.toggle();print('${a.on}:${b.on}');}챌린지
쉬움Parcel을 구현하고, 공개 final 정수 필드 mass와 count를 Parcel(this.mass,this.count)로 초기화하세요. total() 메서드는 두 필드의 곱을 반환합니다. 입력은 1000 이하의 음이 아닌 정수 두 개이며, 출력은 두 수의 곱입니다.
편집 가능한 파일에서는 출력하지 마세요. 제공된 exercise.dart가 입력을 분석하고 출력을 반환하며, 잠긴 드라이버가 공개 API를 별도로 테스트하고 결과를 줄바꿈 문자 하나와 함께 출력합니다.
코드는 Parcel.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.
직접 해보기
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Parcel.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$'),'');
final a=Parcel(6,7);check(a.mass==6 && a.count==7 && a.total()==42);check(Parcel(2,3).total()==6);
stdout.writeln(solve(input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
GDScript 개발자를 위한 Dart의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러