抽象数据类型的形式定义:可以用(D, S, P)三元组表示
D(数据对象)、S(D上的关系集)、P(对D的基本操作集)
ADT 抽象数据类型名{
数据对象的定义;
数据关系的定义;
基本操作的定义(操作名 + 参数表、初始条件、操作结果);
}ADT 抽象数据类型名
圆的例子
ADT Circle{
数据对象:D = {r, x, y | r, x, y均是实数}
数据关系:S = {<r, x, y> | r表示圆的半径,x,y表示圆心坐标}
基本操作:
void circle(&C, r, x, y)
操作结果:构造一个圆
double area(C)
初始条件:圆已存在
操作结果:计算面积
double circunference(C)
初始条件:圆已存在
操作结果:计算周长
...
}ADT Circle
复数的例子
#include<stdio.h>
typedef struct{
float realpart;
float imagpart;
}Complex;
void assign(Complex* C, float realpart, float imagpart) {
C->realpart = realpart;
C->imagpart = imagpart;
}
void add(Complex* C, Complex C1, Complex C2) {
C->realpart = C1.realpart + C2.realpart;
C->imagpart = C1.imagpart + C2.imagpart;
}
void minus(Complex* C, Complex C1, Complex C2) {
C->realpart = C1.realpart - C2.realpart;
C->imagpart = C1.imagpart - C2.imagpart;
}
void multiply(Complex* C, Complex C1, Complex C2) {
...
}
void divide(Complex* C, Complex C1, Complex C2) {
...
}
#include<stdio.h>
#include"Complex.h"
int main() {
Complex C1, C2, C3, C4;
assign(&C1, 8, 6);
assign(&C2, 4, 3);
multiply(&C3, C1, C2);
add(&C4, C1, C2);
divide(&C1, C3, C4)
printf("%f + %fi",C1.realpart, C1.imagpart);
return 0;
}
public class Complex {
float realpart;
float imagpart;
public Complex() {
this(0, 0);
}
public Complex(float realpart, float imagpart) {
this.realpart = realpart;
this.imagpart = imagpart;
}
public static Complex add(Complex C1, Complex C2) {
Complex C = new Complex();
C.realpart = C1.realpart + C2.realpart;
C.imagpart = C1.imagpart + C2.imagpart;
return C;
}
public static Complex minus(Complex C1, Complex C2) {
Complex C = new Complex();
C.realpart = C1.realpart - C2.realpart;
C.imagpart = C1.imagpart - C2.imagpart;
return C;
}
public static Complex multiply(Complex C1, Complex C2) {
...
}
public static Complex divide(Complex C1, Complex C2) {
...
}
}
public ComplexTest {
public static void main(String[] args) {
Complex C1 = new Complex(8, 6);
Complex C2 = new Complex(4, 3);
Complex C3 = new Complex();
Complex C4 = new Complex();
C3 = multiply(C1, C2);
C4 = add(C1, C2);
C1 = divide(C3, C4);
System.out.println(C1);
}