仮想メソッドとoverride
Coddyの「C++開発者のためのC#」コースのレッスン 38/48。
C++とC#はどちらも仮想ディスパッチを使用しますが、C++では値をコピーすると、基底クラスの値に代入したときに派生オブジェクトがスライスされることがあります。C#のクラス参照では、同じスライスのパターンは起こりません。C#では、シグネチャが一致するだけではなく、overrideが必要であり、newによるメンバーの隠蔽とは異なります。
仮想メンバーは派生クラスでオーバーライドできます。overrideを使うと、基底クラスの参照を通じたポリモーフィックなディスパッチが保たれます。newでメンバーを隠蔽するのは別の仕組みです。派生クラスのコンストラクターはbaseを呼び出して、共有状態を初期化できます。サブタイプが基底クラスの契約を守る場合に限り、継承を使用しましょう。
C++の例
#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
class Plan { protected: int unit; public: explicit Plan(int n):unit(n) {} virtual int total(int n) const { return unit*n; } virtual ~Plan()=default; };
class DiscountPlan: public Plan { public: explicit DiscountPlan(int n):Plan(n) {} int total(int n) const override { return Plan::total(n)*9/10; } };
int main() {
DiscountPlan concrete(10); Plan& plan=concrete; cout << plan.total(2) << "\n";
}
C#の宣言部分
class Message { public virtual string Speak() { return "hello"; } }
class LoudMessage : Message { public override string Speak() { return base.Speak().ToUpperInvariant(); } }Main内のC#の文
Message message = new LoudMessage();
Console.WriteLine(message.Speak());これらは要点を絞った学習用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットには関連する宣言と文が示されています。
参照出力:
18C#の出力:
HELLOチャレンジ
簡単Plan.TotalとDiscountPlan.Totalを完成させてください。基本料金はunit * countです。DiscountPlanは、基本料金の整数合計の90パーセントを切り捨てた値を返します。入力が非負なら、積は小さい値に収まります。ドライバーはPlan参照を通じて呼び出し、仮想ディスパッチが行われることを確認します。
ロックされていないC#ファイルを編集してください。表示されているロック済みのMain.csは、説明されている行を読み込み、Exercise.Solveを呼び出し、入力が変更されていないことを検証して、最後に改行を1つ付けて結果を出力します。宣言済みのAPIを維持してください。2つ目のMainを追加したり、診断出力を出したりしないでください。
ロックされたランチャーは、Solveラッパーだけでなく、エクスポートされたヘルパーまたはクラスのAPIも個別にテストします。
自分で試してみよう
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
var a2 = input[2] == "true"; string before2=Snapshot(a2);
Plan p1 = new DiscountPlan(10); Plan p2 = new Plan(10); if (p1.Total(3) != 27 || p2.Total(3) != 30) throw new Exception("Virtual API");
var result = Exercise.Solve(a0,a1,a2);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
if (Snapshot(a2) != before2) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C++開発者のためのC#のすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ