Menu
CoddyTech

抽象基类契约

Coddy 面向 PHP 开发者的 C++ 课程的第 40 课,共 48 课。

PHP 接口和抽象类是名义类型,类似 C++ 基类:类必须声明 implements 或 extends,而类型为 Renderer 的参数会拒绝仅仅拥有匹配方法的对象,不过只有在运行时才会抛出 TypeError。未指定类型的 PHP 代码仍会接受拥有正确方法的任何对象。C++ 抽象基类使用纯虚函数和显式继承。仅仅方法名称匹配并不能建立这种关系,编译器会在程序运行前拒绝这种不匹配。

PHP

<?php
interface Renderer {
    public function render(string $text): string;
}
class Plain implements Renderer {
    public function render(string $text): string {
        return $text;
    }
}
class Bracketed implements Renderer {
    public function render(string $text): string {
        return "[" . $text . "]";
    }
}
function show(Renderer $r): void {
    echo $r->render("hi"), "\n";
}
foreach ([new Plain(), new Bracketed()] as $r) {
    show($r);
}

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

挑战

简单

输入:一行文本。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自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 PHP 开发者的 C++中的所有课

自己练习: C++ 在线编译器