仮想ディスパッチ
Coddyの「Ruby開発者のためのC++」コースのレッスン 39/48。
Rubyのすべてのメソッド呼び出しは実行時にレシーバーのクラスで検索され、superは祖先チェーン上の次の定義を呼び出します。非仮想メソッドというものはありません。C++では、virtualとして宣言された関数のみが動的ディスパッチされ、基底クラスの値を使う場合はスライシングを避ける必要があります。基底クラスのポインターまたは参照を介したC++の仮想関数呼び出しは動的にディスパッチされます。ポリモーフィックな削除には仮想デストラクターが必要です。基底クラスの値へのコピーではスライシングが発生する可能性があります。
Ruby
class Base
def label
"base"
end
end
class Child < Base
def label
super + "!"
end
end
puts Child.new.labelC++
#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はstdinを読み取り、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";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Ruby開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ