상속과 super
Coddy의 PHP 개발자를 위한 GDScript 코스 레슨. 48개 중 27번째.
PHP 클래스와 GDScript 스크립트는 각각 하나의 직접적인 슈퍼클래스를 확장합니다. PHP는 인터페이스와 트레이트를 별도의 메커니즘으로 지원합니다. 접근 제한이나 final 규칙으로 오버라이드가 금지되지 않는 한, 오버라이드된 인스턴스 메서드는 객체 유형에 따라 디스패치됩니다. PHP의 parent::는 상속된 동작을 호출하고, GDScript에서는 super를 사용합니다. 기반 파일과 파생 클래스의 도우미 파일은 별도로 유지하세요. 이 예제에서는 과제의 요금 계산을 공개하지 않고 문장 부호를 덧붙입니다.
완전한 PHP 8.3 프로그램 파일(CLI에서 main.php 실행):
PHP 파일 Base.php:
<?php
declare(strict_types=1);
class Base { public function label(): string { return "base"; } }
PHP 파일 Child.php:
<?php
declare(strict_types=1);
require_once __DIR__."/Base.php"; class Child extends Base { public function label(): string { return parent::label()."!"; } }
PHP 파일 main.php:
<?php
declare(strict_types=1);
require_once __DIR__."/Child.php"; echo (new Child())->label(),"\n";
PHP 출력:
base!완전한 GDScript 예제 파일:
GDScript 파일 demo_base.gd:
class_name DemoBase
extends RefCounted
func label() -> String:
return "base"GDScript 파일 demo_child.gd:
class_name DemoChild
extends DemoBase
func label() -> String:
return super.label() + "!"GDScript 파일 main.gd:
extends Node
func _ready() -> void:
print(DemoChild.new().label())GDScript 출력:
base!챌린지
쉬움BaseFee.cost(units:int)->int를 units*3으로 구현하세요. DiscountFee는 BaseFee를 상속하고, 상속된 동작을 사용해 cost를 max(base cost-2,0)로 재정의합니다. Solve에서는 DiscountFee를 사용합니다.
입력은 stdin으로 전달되는 하나의 JSON 배열입니다. 잠긴 main은 이를 파싱하고, 공개 API를 호출한 다음 반환된 텍스트 앞에 result=를 붙여 출력하고 줄바꿈합니다. 어떤 도우미 함수도 출력하면 안 됩니다. 입력 사례를 처리하기 전에 독립적인 고정 프로브를 통해 필수 API 동작을 검증합니다. 이 프로브는 구현 방식을 제한하지 않습니다.
코드는 base_fee.gd, discount_fee.gd, exercise.gd에 작성하세요. main.gd에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 각 class_name 형식은 이름이 지정된 파일에 두세요.
직접 해보기
extends Node
func contract_ok(data: Array) -> bool:
if BaseFee.new().cost(4) != 12 or DiscountFee.new().cost(4) != 10 or DiscountFee.new().cost(0) != 0: return false
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
PHP 개발자를 위한 GDScript의 모든 레슨
직접 연습해 보세요: 온라인 GDScript 컴파일러