Menu
CoddyTech

抽象基底クラスの契約

Coddyの「Go開発者のためのC++」コースのレッスン 40/48。

Goのインターフェースはメソッドセットによって暗黙的に満たされます。C++の抽象基底クラスでは明示的な継承が必要であり、メソッドが一致するだけでは不十分です。C++の抽象基底クラスでは純粋仮想関数と明示的な継承を使用します。メソッド名が一致するだけでは、この関係は確立されません。

Go

package main
import (
 "fmt"
 "strings"
)
type Channel interface { Send(string) string }; type Loud struct{}; func (Loud) Send(text string) string { return strings.ToUpper(text) }
func main() {
 var c Channel=Loud{}; fmt.Println(c.Send("hi"))
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Shape{virtual ~Shape()=default;virtual std::string name()const=0;};struct Square:Shape{std::string name()const override{return "square";}};
int main(){
Square x;const Shape& s=x;std::cout<<s.name()<<"\n";
}

各プログラムを個別にトレースしてください。これらの例では、課題とは異なる操作やデータを使って概念を示しています。ソースとターゲットの出力が一致するとは限りません。

challenge icon

チャレンジ

簡単

入力:テキスト1行。Channel は純粋仮想関数 send と仮想デストラクターを宣言します。Plain はテキストを返し、Tagged はタグ、コロン、テキストを連結して返します。ドライバーは Plain の結果に続けて、タグが log の Tagged の結果を出力します。

編集可能なモジュール:Channel.cpp、Channel.hpp、Plain.cpp、Plain.hpp、Tagged.cpp、Tagged.hpp。各必須型には、それぞれの名前が付いたヘッダーと実装があります。すべての公開シグネチャを維持してください。ロックされた main.cpp は標準入力を読み取り、API を直接呼び出します。また、記載されている箇所では公開 API の動作も独立して確認します。API 内で出力せず、戻り値を返してください。整数の入力値と結果は符号付き int の範囲内です。特に記載がない限り、テキストは ASCII です。

自分で試してみよう

#include "Channel.hpp"
#include "Plain.hpp"
#include "Tagged.hpp"
#include <iostream>
int main(){
{Plain p;Tagged t("warn");const Channel& a=p;const Channel& b=t;if(a.send("probe")!="probe"||b.send("other")!="warn:other")return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
Plain a;Tagged b("log");std::string s=rows.empty()?"":rows[0];for(const Channel* p:std::vector<const Channel*>{&a,&b})std::cout<<p->send(s)<<"\n";
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Go開発者のためのC++のすべてのレッスン

自分で練習してみよう: C++オンラインコンパイラ