开放类与重写
Coddy 面向 C++ 开发者的 Kotlin 课程的第 39 课,共 48 课。
C++ 虚方法可显式启用运行时分发,并且支持多重类继承。Kotlin 最多只能继承一个类,且要求目标类或方法声明为 open 或 abstract,并使用 override 标注重写。super 可以复用继承的行为。当目标是替换某种策略而非创建真正的子类型时,应优先选择组合。
C++
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <optional>
#include <functional>
#include <sstream>
#include <variant>
#include <memory>
#include <cctype>
#include <stdexcept>
struct Base {virtual int cost()const{return 4;}virtual ~Base()=default;};struct Express:Base {int cost()const override{return Base::cost()+3;}};
int main() {
std::cout << std::boolalpha;
Express item;std::cout << item.cost() << "\n";
}
Kotlin
open class Animal{open fun voice():String="?"};class Cat:Animal(){override fun voice():String="mew"}
fun main(){
val a:Animal=Cat()
println(a.voice())
}迁移陷阱
Kotlin 的扩展点是显式的;普通方法并非都是可重写的。
在单独的练习中应用此概念。演示使用的是不同的操作或模型;请保留要求的任务 API,并让锁定的入口点负责输入和输出。
挑战
简单输入为非负的基础价格,以及不大于该价格的折扣。实现 open Pass(price:Int) 及其 open cost(),以及继承 Pass 并使用 super 重写 cost 的 DiscountPass(price:Int,discount:Int)。先返回基础费用,再返回折扣后的费用。
实现可编辑的文件,并从 Exercise.solve(input: List<String>) 返回结果。请勿在可编辑的方法内部打印。可见的被锁定文件 Main.kt 会读取所有输入行,并打印你返回的文本(末尾带有一个换行符)。Text.kt 提供了解析和格式化的辅助工具。除非说明了更窄的范围,否则所有算术结果均符合 Int 范围。
可编辑的文件:Pass.kt、DiscountPass.kt、Exercise.kt、Text.kt。只有 Main.kt 包含 main;它是被锁定的,且为最后一个文件。所有文件都在同一个包中一起编译。
被锁定的驱动程序会在新对象和替代协作者上独立调用所需的公共 API。请实现这些行为,仅重现固定测试用例的输出是不够的。
亲手试试
fun main() {
val input = generateSequence { readlnOrNull() }.toList()
val p:Pass=DiscountPass(12,5);check(p.cost()==7 && Pass(8).cost()==8)
println(Exercise.solve(input))
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 Kotlin中的所有课
自己练习: Kotlin 在线编辑器