Menu
CoddyTech

组合对象

Coddy 面向 C++ 开发者的 GDScript 课程的第 29 课,共 48 课。

按值存储的 C++ 成员拥有其自身的值,而指针或引用可以共享协同对象。shared_ptr 显式表达共享所有权。GDScript 类引用字段同样共享对象,且 RefCounted 会保留它们。shared_ptr 和 RefCounted 都不会自动回收强所有权循环;请使用弱链接或无环所有权图。构造函数注入使替代协同对象易于测试。该示例通过共享所有权存储传入的 note,因此后续的修改在 envelope 中仍然可见。

完整的 C++ 对比。将列出的文件保存在一起,并使用 C++20 编译 .cpp 文件;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` 必须会影响账单。`Solve` 使用 `[rate,units]`。

输入是标准输入(stdin)上的一个 JSON 数组。被锁定的 `main` 会解析它,调用公开 API,并打印 `result=`,后跟返回的文本和换行符。任何辅助函数都不应进行打印。独立的固定探测程序会在输入用例之前验证所需的 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 在线编译器