仮想関数のディスパッチ
Coddyの「Swift開発者のためのC++」コースのレッスン 39/48。
Swiftのクラスメソッドは、デフォルトで動的ディスパッチされます。メソッドがfinalでない限り、基底クラス型の参照を通じて呼び出すとoverrideされたメソッドが選択されます。一方、構造体には継承がありません。C++ではデフォルトの動作が逆です。基底クラスのポインターや参照を通じた呼び出しが動的にディスパッチされるのは、基底クラスで関数をvirtualと宣言した場合に限られます。ポリモーフィックな削除には仮想デストラクターが必要です。派生オブジェクトを基底クラスの値にコピーするとスライスが発生しますが、Swiftのクラス参照ではこのようなことは起こりません。
Swift
class Sound {
func play() -> String { "tap" }
}
class Chime: Sound {
override func play() -> String { "ding" }
}
let s: Sound = Chime()
print(s.play())
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Sound{virtual ~Sound()=default;virtual std::string play()const{return "tap";}};struct Chime:Sound{std::string play()const override{return "ding";}};
int main(){
Chime x;const Sound& s=x;std::cout<<s.play()<<"\n";
}
各プログラムを個別に追ってください。これらの例では、課題とは異なる操作やデータを使って概念を説明しています。ソースの出力とターゲットの出力が一致するとは限りません。
チャレンジ
簡単入力: 基本料金と追加料金。いずれも非負です。Fee.amount は基本料金を返します。ExtraFee は Fee を public 継承し、amount をオーバーライドして追加料金を加算します。ドライバーは const Fee 参照を通じて呼び出します。仮想デストラクターを使用してください。
編集可能なモジュール: Fee.cpp、Fee.hpp、ExtraFee.cpp、ExtraFee.hpp。必要な型はそれぞれ、名前付きのヘッダーと実装ファイルを持ちます。すべての public シグネチャを維持してください。ロックされた main.cpp は標準入力を読み取り、API を直接呼び出します。また、記載がある場合は public API の動作を個別に確認します。API 内で出力するのではなく、値を返してください。整数の入力と結果は signed int の範囲内に収まり、特に指定がない限りテキストは ASCII です。
自分で試してみよう
#include "Fee.hpp"
#include "ExtraFee.hpp"
#include <iostream>
int main(){
{Fee a(5);ExtraFee b(2,7);const Fee& r=b;if(a.amount()!=5||r.amount()!=9)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 a,b;in>>a>>b;ExtraFee f(a,b);const Fee& ref=f;std::cout<<ref.amount()<<"\n";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Swift開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ