Menu
CoddyTech

コンストラクタによる初期化

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

GDScriptでは、まず各メンバーに宣言順でそのvar行の値が設定され、その後に_initが実行されて、それらの値が上書きされます。_initはオーバーロードできないため、省略可能な引数にはデフォルト値を使います。C++のコンストラクターは、コンストラクター本体の実行前に基底クラスとメンバーのサブオブジェクトを初期化し、不変条件を確立します。メンバー初期化子リストは各フィールドを値で直接構築し、実際の初期化はメンバーの宣言順に行われます。

GDScript

extends Node

class Score:
    var points: int = 1
    var bonus: int = points * 2
    func _init(p: int = 0) -> void:
        points = p

func _ready() -> void:
    var a := Score.new(5)
    var b := Score.new()
    print(a.points, " ", a.bonus, " ", b.points)

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Badge {std::string name;explicit Badge(std::string n):name(std::move(n)){} };
int main(){
Badge b("Ada");std::cout<<b.name<<"\n";
}

各プログラムを個別に追ってください。これらの例では、課題とは異なる操作やデータを使って概念を説明しています。ソースと出力先の結果が一致するとは限りません。

challenge icon

チャレンジ

簡単

入力: 整数の開始残高と、0以上の入金額。Wallet は max(start,0) で初期化されます。add は残高を増やし、balance は現在の金額を返します。

編集可能なモジュール: Wallet.cpp、Wallet.hpp。必要な各型には、それぞれ名前付きのヘッダーと実装があります。すべての公開シグネチャを維持してください。ロックされた main.cpp は標準入力を読み取り、API を直接呼び出します。また、指定されている場合は公開 API の動作を個別に確認します。API 内で出力せず、戻り値を返してください。整数の入力と結果は符号付き int の範囲内に収まります。特に指定がない限り、テキストは ASCII です。

自分で試してみよう

#include "Wallet.hpp"
#include <iostream>
int main(){
{Wallet a(-2),b(7);a.add(3);a.add(4);if(a.balance()!=7||b.balance()!=7)return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n,d;in>>n>>d;Wallet w(n);w.add(d);std::cout<<w.balance()<<"\n";
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

GDScript開発者のためのC++のすべてのレッスン

自分で練習してみよう: C++オンラインコンパイラ