虚函数分派
Coddy 面向 Go 开发者的 C++ 课程的第 39 课,共 48 课。
Go 的嵌入会提升方法,但它不是类继承。C++ 虚函数分派是一种显式声明的层次机制。通过基类指针或引用调用 C++ 虚函数时,会进行动态分派。多态删除需要虚析构函数;复制到基类值中可能会发生对象切片。
Go
package main
import ("fmt")
type Sound struct{};func (Sound) Play()string{return "tap"};type Chime struct{Sound};func (Chime) Play()string{return "ding"}
func main(){
x:=Chime{};fmt.Println(x.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";
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示该概念,不要认为源语言和目标语言的输出会相同。
挑战
简单输入:基本费用和奖金,均为非负数。Fee.amount 返回基本费用。ExtraFee 公有继承自 Fee,并重写 amount 以加上奖金。驱动程序通过 const Fee 引用调用。使用虚析构函数。
可编辑模块:Fee.cpp、Fee.hpp、ExtraFee.cpp、ExtraFee.hpp。每种必需类型都有各自命名的头文件和实现文件。保留所有公共签名。锁定的 main.cpp 从 stdin 读取数据,并直接调用 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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 C++中的所有课
自己练习: C++ 在线编译器