Menu
CoddyTech

합성 객체

Coddy의 C++ 개발자를 위한 GDScript 코스 레슨. 48개 중 29번째.

값으로 저장된 C++ 멤버는 자체 값을 소유하는 반면, 포인터나 참조는 협력 객체를 공유할 수 있습니다. shared_ptr은 공유 소유권을 명시적으로 나타냅니다. GDScript 클래스 참조 필드 역시 객체를 공유하며, RefCounted가 이를 유지합니다. shared_ptr과 RefCounted 모두 강한 소유권 순환을 자동으로 회수하지 않으므로, 약한 참조나 비순환 소유권 그래프를 사용하세요. 생성자 주입을 사용하면 대체 협력 객체를 테스트할 수 있습니다. 이 예제는 제공된 note를 공유 소유권을 통해 저장하므로, 나중에 변경한 내용이 envelope에도 그대로 보입니다.

전체 C++ 비교입니다. 나열된 파일들을 함께 저장하고 .cpp 파일들을 C++20으로 컴파일하세요. main이 진입점입니다.

C++ 파일 note.hpp:

#pragma once
#include <string>
struct Note { std::string text="a"; };

C++ 파일 envelope.hpp:

#pragma once
#include <memory>
#include <utility>
#include "note.hpp"
struct Envelope { std::shared_ptr<Note> note; explicit Envelope(std::shared_ptr<Note> n):note(std::move(n)) {} };

C++ 파일 main.cpp:

#include <iostream>
#include "envelope.hpp"
int main() { auto n=std::make_shared<Note>(); Envelope e(n); n->text="b"; std::cout << e.note->text << '\n'; }

C++ 출력:

b

GDScript 예제 파일 demo_note.gd:

class_name DemoNote
extends RefCounted
var text: String = "a"

GDScript 예제 파일 demo_envelope.gd:

class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
	note = value

GDScript 예제 파일 main.gd:

extends Node

func _ready() -> void:
	var note: DemoNote = DemoNote.new()
	var envelope: DemoEnvelope = DemoEnvelope.new(note)
	note.text = "b"
	print(envelope.note.text)

GDScript 출력:

b
challenge icon

챌린지

쉬움

cost(units:int)를 포함하는 RateRule(cents:int)를 구현하세요. BillBox(rule:RateRule)는 전달받은 규칙을 저장하며 total(units:int)는 해당 규칙에 처리를 위임합니다. 나중에 rule.cents를 변경하면 bill에 영향을 미쳐야 합니다. Solve는 [rate,units]를 사용합니다.

입력은 stdin을 통한 하나의 JSON 배열입니다. 잠긴 main은 이를 파싱하고 공개 API를 호출하여 result= 뒤에 반환된 텍스트와 개행 문자를 출력합니다. 어떠한 헬퍼도 출력해서는 안 됩니다. 독립된 고정 검사(probe)는 입력 케이스 이전에 필요한 API 동작을 검증하며, 구현 스타일을 강제하지 않습니다.

코드는 rate_rule.gd, bill_box.gd, exercise.gd에 작성합니다. main.gd에는 제공된 입력/출력 코드가 포함되어 있으며 수정할 수 없습니다. 각 class_name 타입을 이름이 지정된 파일에 유지하세요.

직접 해보기

extends Node

func contract_ok(data: Array) -> bool:
	var rule: RateRule = RateRule.new(2)
	var bill: BillBox = BillBox.new(rule)
	rule.cents = 7
	if rule.cost(3) != 21 or bill.total(3) != 21: 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))
quiz icon실력 점검

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

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

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