Menu
CoddyTech

虚拟分派

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";
}

分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示概念,不要假设源代码和目标代码的输出相同。

challenge icon

挑战

简单

输入:基础费用和奖金,均为非负数。Fee.amount 返回基础费用。ExtraFee 公有派生自 Fee,并重写 amount 以加上奖金。驱动程序通过 const Fee 引用调用。使用虚析构函数。

可编辑模块:Fee.cpp、Fee.hpp、ExtraFee.cpp、ExtraFee.hpp。每种必需类型都有自己的命名头文件和实现文件。保留所有公有签名。已锁定的 main.cpp 会读取标准输入并直接调用 API。它还会在说明中指定的情况下,独立检查公有 API 的行为。在 API 内返回值,而不是打印。整数输入和结果都在有符号 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";
}
quiz icon自我测试

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

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

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