Menu
CoddyTech

合成オブジェクト

Coddyの「C++開発者のためのGDScript」コースのレッスン 29/48。

値で格納された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

チャレンジ

簡単

RateRule(cents:int) に cost(units:int) を実装してください。BillBox(rule:RateRule) は渡されたルールを保持し、total(units:int) はそれに処理を委譲します。後から rule.cents を変更した場合、請求額(bill)に反映される必要があります。Solve は [rate,units] を使用します。

入力は stdin からの1つの 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オンラインコンパイラ