抽象基类行为
Coddy 面向 C 开发者的 Dart 课程的第 35 课,共 48 课。
C 没有抽象类。共享行为是一个接收基础结构体的函数,它通过函数指针调用每种具体类型提供的函数,因此共享代码会将调用分派给实际对象的专用部分。C 不会阻止你创建一个函数指针为 null 的基础结构体,而调用这个指针会产生未定义行为。Dart 抽象类将具体的共享方法与抽象要求结合起来,并且编译器会拒绝直接实例化它。
抽象类不能直接实例化。它可以将抽象要求与具体的共享行为结合起来。具体方法可以调用子类提供的专用重写方法。
完整的 C 程序:
#include <stdio.h>
struct shape {
const char *(*name)(void); /* 每种具体形状都必须提供的部分 */
};
static void shape_label(const struct shape *s) { printf("shape:%s\n", s->name()); }
static const char *circle_name(void) { return "circle"; }
int main(void) {
const struct shape circle = {circle_name};
shape_label(&circle);
return 0;
}
完整的 Dart 程序:
abstract class Shape{String name();String label()=>'shape:'+name();}
class Circle extends Shape{String name()=>'circle';}
void main(){print(Circle().label());}挑战
简单实现抽象类 Charge,其中包含抽象方法 cost(int units) 和具体方法 pair(int a,int b),使用动态分派将两项费用相加。FlatCharge(int fee) 继承 Charge:units 为 0 时,cost 为 0;否则为 fee。UnitCharge(int rate) 继承 Charge:cost 等于 rate 乘以 units。输入包括模式 flat 或 unit、金额、a 和 b,它们都是不超过 100 的非负整数。输出 pair。
不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立测试公共 API,并在结果末尾打印一个换行符。
你的代码要写在 Charge.dart、FlatCharge.dart、UnitCharge.dart 和 exercise.dart 中。main.dart 中包含提供的输入输出代码,不能编辑。
亲手试试
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Charge.dart';
import 'FlatCharge.dart';
import 'UnitCharge.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final Charge a=FlatCharge(7),b=UnitCharge(3);check(a.cost(0)==0 && a.cost(2)==7 && a.pair(1,2)==14);check(b.cost(4)==12 && b.pair(2,3)==15);
stdout.writeln(solve(input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Dart中的所有课
自己练习: Dart 在线编译器