3.2.5 编程(www.cppentry.com)题
【例3.19】设计一个类Rect,要求有下列成员函数。
(1)Move():从一个位置移动到另一个位置。
(2)Size():改变矩形的大小。
(3)Where():返回矩形左上角的坐标值。
(4)Area():计算矩形面积。
解:由于Where()成员函数返回矩形左上角的坐标值,即两个参数,所以采用引用类型。本题程序如下:
- #include <iostream.h>
- class Rect
- { int x,y; //左上角坐标
- int w,h; //宽度和高度
- public:
- Rect(int x1,int y1,int w1,int h1)
- { x=x1; y=y1;
- w=w1; h=h1;
- }
- void Move(int x1,int y1) { x=x1;y=y1; }
- void Size(int w1,int h1) { w=w1;h=h1; }
- void Where(int &x1,int &y1) { xx1=x;yy1=y; }
- int Area() { return w*h; }
- };
- void main()
- { Rect r(2,3,20,10);
- int x,y;
- cout << "矩形面积:" << r.Area() << endl;
- cout << "移动到(5,4)" << endl;
- r.Move(5,4);
- cout << "改变宽为6,高为3" << endl;
- r.Size(6,3);
- r.Where(x,y);
- cout << "左上角:(" << x << "," << y << ")" << endl;
- cout << "矩形面积:"<< r.Area()<<endl;
- }
【例3.20】编写一个程序,有单链表的节点类型如下:
- typedef struct node
- { int no;
- struct node *next;
- } Node;
设计如下函数。
void create(Node *h):建立不带头节点的单链表h。
int len(Node *h):返回不带头节点的单链表h的长度。
void del(Node *h,int i):删除不带头节点的单链表h的第i个节点。
void disp(Node *h):输出不带头节点的单链表h的所有节点值。
解:程序如下:
- #include <iostream.h>
- #include <malloc.h>
- typedef struct node //单链表节点类型
- { int no;
- struct node *next;
- } Node;
- void create(Node *&h) //建立一个链表,h为链表的开始结点指针,一定要使用引用类型
- { Node *s,*r;
- int n;
- h=NULL;
- cout << "数序(以负数结束):";
- cin >> n;
- while (n>0)
- { s=(Node *)malloc(sizeof(Node));
- s->nno=n;s->next=NULL;
- if (h==NULL)
- { h=s;
- r=h; //r指向链表的最后一个节点
- }
- else
- { r->next=s; //*s插入最后
- r=s; //r指向链表的最后一个节点
- }
- cin >> n;
- }
- }
- int len(const Node *h) //求链表长度
- { int i=0;
- while (h!=NULL)
- { i++;
- hh=h->next;
- }
- return i;
- }
- void del(Node *&h,int i) //删除单链表h的第i个节点
- { Node *p=h,*q;
- if (i<1 || i>len(h)) //i值错误
- return;
- if (i==1) //删除第1个节点
- { hh=h->next;
- free(p);
- }
- else //删除其他节点
- { while (i-->2)
- pp=p->next; //找到第i-1个节点*p
- q=p->next; //q指向被删节点
- p->next=q->next; //删除*q节点
- free(q); //释放其空间
- }
- }
- void disp(const Node *h) //显示单链表
- { cout << "链表:";
- while (h!=NULL)
- { cout << h->no << " ";
- hh=h->next;
- }
- cout << endl;
- }
- void main()
- { Node *head;
- int i;
- create(head);
- disp(head);
- cout << "链表长度:" << len(head) << endl;
- cout << "删除第几个节点:";
- cin >> i;
- del(head,i);
- disp(head);
- }
应特别注意,del(Node *&h,int i)和create(Node *&h)这两个函数的h形参一定要用指针引用类型,否则,前者在i=1时程序运行出错,后者无法建立单链表。另外,有些函数可以使用常类型的形参,原因请读者思考。