《C++编程例题.doc》由会员分享,可在线阅读,更多相关《C++编程例题.doc(7页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、1.定义复数类,要求:(1)定义两个重载的构造函数,一个无参数,一个带有两个参数(2)用重载运算符“”、“”实现两个复数的加、减法(3)用重载运算符“”实现复数的输入输出。1. #includeusing namespace std;class fushupublic:fushu()shi=0.0;xu=0.0;fushu(double x,double y)shi=x;xu=y;friend fushu operator +(fushu&,fushu&);friend fushu operator -(fushu&,fushu&);friend std:ostream& operator (
2、std:istream &oo,fushu& s1);protected:double shi;double xu;fushu operator +(fushu& s1,fushu& s2)double x1=s1.shi+s2.shi;double x2=s1.xu+s2.xu;fushu result(x1,x2);return result;fushu operator -(fushu& s1,fushu& s2)double x1=s1.shi-s2.shi;double x2=s1.xu-s2.xu;fushu result(x1,x2);return result;std:ostr
3、eam& operator =0)oos1.shi+s1.xui;else oos1.shis1.xu(std:istream &oo,fushu& s1)oos1.shi;oos1.xu;return oo; void main()fushu a(3,4);fushu b(4,5);fushu c;c=a+b;coutc;2设计并测试一个简单的栈类Stack,数据按照先进后出的方法操作。提供如下功能:判断栈是否为空、出栈和入栈。栈中数据元素的类型不限。#includeusing namespace std;class Stackpublic:Stack()top=-1;ps=0;bool n
4、ull_stack()if(top=-1)return false;else return true;void push(int e)ps=new int;top+;pstop=e;bool insert()if(top=-1)return false;else top-;return true;protected:int top;int * ps;3编写使用简单选择排序和直接插入排序方法进行排序的函数模版,并编制主函数分别对int型、char型数据进行排序。3、#includeusing namespace std;template void charu(T a,int n)int inde
5、x=0,inserter=0,i;for(i=1;i=0&inserteraindex)aindex+1=aindex;index-;aindex+1=inserter;for(i=0;in;i+)coutai ;coutendl;template void xuanze(T a,int n)int temp,i,j,k;for(i=0;in-1;i+)j=i;for(k=i+1;kn;k+)if(akai)j=k;if(i!=j)temp=ai;ai=aj;aj=temp;for(i=0;in;i+)coutai ;coutendl;void main()int i;int a6=1,3,5
6、,3,6,7;for(i=0;i6;i+)coutai ;coutendl;xuanze(a,6);char b5=4,5,6,5,5;for(i=0;i5;i+)coutbi ;coutendl;xuanze(b,5);4.定义一个抽象基类Shape用以计算几何形状的面积,并从此基类派生出长方形类和圆形类。编写适当函数,实现通过基类指针来调用派生类中的虚函数,计算不同形状的面积。#include#includeusing namespace std;class shapepublic:shape(double x,double y)xcoord=x;ycoord=y;virtual doub
7、le area()=0;protected:double xcoord,ycoord;class circle:public shapepublic:circle(double x,double y,double r):shape(x,y),radius(r);virtual double area()return 3.14*radius*radius;protected:double radius;class rectangle:public shapepublic:rectangle(double x1,double y1,double x2,double y2):shape(x1,y1)
8、,x2coord(x2),y2coord(y2);virtual double area()return fabs(x2coord-xcoord)*(y2coord-ycoord);protected:double x2coord,y2coord;void func(shape& s)couts.area()endl;void main()circle a(3,4,5);func(a);5定义一个字符串类String,数据成员为字符串的长度和指向字符串存储空间(要求动态分配堆内存)的指针,并定义以下成员函数:(1)定义构造函数、拷贝构造函数和析构函数(2)重载运算符”=”实现两个String类
9、对象之间的赋值5. #include#includeusing namespace std;class Stringpublic:String(char *p)size=strlen(p);ps=new charsize+1;if(ps!=0)strcpy(ps,p);String(String& s)size=strlen(s.ps);ps=new charsize+1;if(ps!=0)strcpy(ps,s.ps);void display()coutpsendl;coutsizeendl;String()coutdestructingendl;delete ps;String& operator =(String &s)delete ps; size=s.size; ps=s.ps; return *this;protected:char *ps;int size;void main()String a(myname);a.display();String b(noname);b=a;b.display();6作业中的其他习题
限制150内