コンストラクタによる初期化
Coddyの「C開発者のためのC++」コースのレッスン 33/48。
Cの構造体は、集成体構文または明示的なセットアップ関数を通じて初期化します。C++のコンストラクターは使用前に不変条件を確立し、メンバー初期化子リストはフィールドを直接初期化します。メンバーは、初期化子リスト内での順序にかかわらず、宣言された順序で初期化されます。
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct Badge {const char* name;};void init(struct Badge* b,const char* name){b->name=name;}
int main(void){
struct Badge b;init(&b,"Ada");puts(b.name);
return 0;
}
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";
}
各プログラムを個別にたどってください。これらの例では、課題とは異なる操作やデータを使って概念を示しています。ソースの出力とターゲットの出力が一致するとは限りません。
チャレンジ
簡単入力: 整数の初期残高と、0以上の入金額。Wallet は max(start,0) で初期化され、add は残高を増やし、balance は現在の金額を返します。
編集可能なモジュール: Wallet.cpp、Wallet.hpp。必要な各型には、それぞれ名前付きのヘッダーと実装があります。すべての公開シグネチャを保持してください。ロックされた main.cpp は stdin を読み取り、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";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ