コンストラクタによる初期化
Coddyの「C#開発者のためのC++」コースのレッスン 33/48。
C#のコンストラクタチェーンは、所有するサブオブジェクトに対するC++のメンバー初期化リストとは異なります。C++のコンストラクタは不変条件を確立します。メンバー初期化リストはフィールドを初期化し、実際の初期化はメンバーの宣言順に従います。
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
class Bag { public List<int> Items=new List<int>(); }
static void Main() {
var a=new Bag(); var b=new Bag(); a.Items.Add(1); Console.WriteLine(b.Items.Count);
}
}
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は標準入力を読み取り、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++オンラインコンパイラ