仮想ディスパッチ
Coddyの「C開発者のためのC++」コースのレッスン 39/48。
Cでは関数ポインターを使ってディスパッチを模倣できますが、言語レベルのクラス継承はありません。C++の仮想関数は、基底クラスの参照またはポインターを通じてオーバーライドを選択します。基底クラスのポインターを通じて派生オブジェクトを削除するには、基底クラスのデストラクターを仮想にする必要があります。ポリモーフィックなオブジェクトを値渡しすると、派生部分がスライスされて失われることがあります。
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
const char* ding(void){return "ding";}struct Sound{const char*(*play)(void);};
int main(void){
struct Sound s={ding};puts(s.play());
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 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";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ