操作题训练(一)
一、基本操作题
// proj1.cpp #include<iostream> #pragma warning (disable:4996) using namespace std; class Salary{ public: Salary(const char *id, double the_base, double the_bonus, double the_tax) // ERROR **********found********** : the_base(base), the_bonus(bonus), the_tax(tax) { staff_id=new char[strlen(id)+1]; strcpy(staff_id,id); } // ERROR **********found********** ~Salary(){ delete *staff_id; } double getGrossPay()const{ return base+bonus; } //返回应发项合计 double getNetPay()const{ return getGrossPay()-tax; } //返回实发工资额 private: char *staff_id; //职工号 double base; //基本工资 double bonus; //奖金 double tax; //代扣个人所得税 }; int main() { Salary pay("888888", 3000.0, 500.0, 67.50); cout<<"应发合计:"<<pay.getGrossPay()<<" "; cout<<"应扣合计:"<<pay.getGrossPay()-pay.getNetPay()<<" "; // ERROR **********found********** cout<<"实发工资:"<<pay::getNetPay()<<endl; return 0; }
二、简单应用题
// proj2.cpp #include <iostream> using namespace std; class Array { public: Array(int size) // 构造函数 { //**********found********** _p = __________; _size = size; } ~Array() { delete [] _p; } // 析构函数 void SetValue(int index, int value) // 设置指定元素的值 { if ( IsOutOfRange(index) ) { cerr << "Index out of range!" << endl; return; } //**********found********** __________; } int GetValue(int index) const // 获取指定元素的值 { if ( IsOutOfRange(index) ) { cerr << "Index out of range!" << endl; return -1; } //**********found********** __________; } int GetLength() const { return _size; } // 获取元素个数 private: int *_p; int _size; bool IsOutOfRange(int index) const // 检查索引是否越界 { //**********found********** if (index < 0 || __________) return true; else return false; } }; int main() { Array a(10); for (int i = 0; i < a.GetLength(); i++) a.SetValue(i, i+1); for (int j = 0; j < a.GetLength()-1; j++) cout << a.GetValue(j) << ", "; cout << a.GetValue(a.GetLength()-1) << endl; return 0; }
三、综合应用题
//Polynomial.h #include<iostream> #include<string> using namespace std; class Polynomial{ //“多项式”类 public: Polynomial(double coef[], int num):coef(new double[num]),num_of_terms(num){ for(int i=0;i<num_of_terms;i++) this->coef[i]=coef[i]; } ~Polynomial(){ delete[] coef; } //返回指定次数项的系数 double getCoefficient(int power)const{ return coef[power]; } //返回在x等于指定值时多项式的值 double getValue(double x)const; private: //系数数组,coef[0]为0次项(常数项)系数,coef[1]为1次项系数,coef[2]为2次项(平方项)系数,余类推。 double *coef; int num_of_terms; }; void writeToFile(string path);
//Polynomial.cpp #include"Polynomial.h" double Polynomial::getValue(double x)const{ // 多项式的值value为各次项的累加和 double value=coef[0]; // 用value累计多项式的值,初值为常数项值 //********333******** //********666******** }
//proj3.cpp #include "Polynomial.h" int main(){ double p1[]={5.0, 3.4, -4.0, 8.0}, p2[]={0.0, -5.4, 0.0, 3.0, 2.0}; Polynomial poly1(p1, sizeof(p1)/sizeof(double)), poly2(p2, sizeof(p2)/sizeof(double)); cout<<"Value of p1 when x=2.5 : "<<poly1.getValue(2.5)<<endl; cout<<"Value of p2 when x=3.0 : "<<poly2.getValue(3.0)<<endl; writeToFile(".\\"); return 0; }
操作题训练(二)
一、基本操作题
//proj1.cpp #include<iostream> #pragma warning (disable:4996) using namespace std; class Score{ public: Score(const char *the_course, const char *the_id, int the_normal, int the_midterm, int the_end_of_term) : course(the_course), normal(the_normal), midterm(the_midterm) , end_of_term(the_end_of_term){ // ERROR **********found********** strcpy(the_id,student_id); } const char *getCourse()const{ return course; } //返回课程名称 // ERROR **********found********** const char *getID()const{ return &student_id; } //返回学号 int getNormal()const{ return normal; } //返回平时成绩 int getMidterm()const{ return midterm; } //返回期中考试成绩 int getEndOfTerm()const{ return end_of_term; } //返回期末考试成绩 int getFinal()const; //返回总评成绩 private: const char *course; //课程名称 char student_id[12]; //学号 int normal; //平时成绩 int midterm; //期中考试成绩 int end_of_term; //期末考试成绩 }; //总评成绩中平时成绩占20%,期中考试占30%,期末考试占50%,最后结果四舍五入为一个整数 // ERROR **********found********** int getFinal()const{ return (int)(normal*0.2+midterm*0.3+end_of_term*0.5+0.5); } int main(){ char English[]="英语"; Score score(English,"12345678",68,83,92); cout<<"学号:"<<score.getID()<<" "; cout<<"课程:"<<score.getCourse()<<" "; cout<<"总评成绩:"<<score.getFinal()<<endl; return 0; }
二、简单应用题
//shape.h class Shape{ public: virtual double perimeter()const { return 0; } //返回形状的周长 virtual double area()const { return 0; } //返回形状的面积 virtual const char* name()const { return "抽象图形"; } //返回形状的名称 }; class Point{ //表示平面坐标系中的点的类 double x; double y; public: //**********found********** Point (double x0,double y0):____________________{ }//用x0、y0初始化数据成员x、y double getX()const{ return x;} double getY()const{ return y;} }; class Triangle: public Shape{ //**********found********** _____________________________________ ; //定义三角形的三个顶点 public: Triangle(Point p1,Point p2,Point p3):point1(p1),point2(p2),point3(p3){} double perimeter()const; double area()const; const char* name()const{ return "三角形"; } };
//shape.cpp #include "shape.h" #include <cmath> double length(Point p1,Point p2) { return sqrt((p1.getX()-p2.getX())*(p1.getX()-p2.getX())+ (p1.getY()-p2.getY())*(p1.getY()-p2.getY())); } double Triangle::perimeter()const { //一个return语句,它利用length函数计算并返回三角形的周长 //**********found********** ________________________________________________________________________ ; } double Triangle::area()const { double s=perimeter()/2.0; return sqrt(s*(s-length(point1,point2))* (s-length(point2,point3))* (s-length(point3,point1))); }
//proj2.cpp #include "shape.h" #include <iostream> using namespace std; //**********found********** ______________________________ // show函数的函数头(函数体以前的部分) { cout<<"此图形是一个" << shape->name() << ", 周长="<<shape->perimeter() << ", 面积="<<shape->area()<<endl; } int main( ) { Shape *s = new Shape; Triangle *tri = new Triangle(Point(0,2),Point(2,0),Point(0,0)); show(s); show(tri); return 0; }
三、综合应用题
//Array.h #include<iostream> using namespace std; template<class Type, int m> class Array { //数组类 public: Array(Type b[], int mm) { //构造函数 for(int i=0; i<m; i++) if(i<mm) a[i]=b[i]; else a[i]=0; } void Contrary(); //交换数组a中前后位置对称的元素的值 int Length() const{ return m; } //返回数组长度 Type operator [](int i)const { //下标运算符重载为成员函数 if(i<0 || i>=m) {cout<<"下标越界!"<<endl; exit(1);} return a[i]; } private: Type a[m]; }; void writeToFile(const char *); //不用考虑此语句的作用
//proj3.cpp #include "Array.h" //交换数组a中前后位置对称的元素的值 template<class Type, int m> void Array<Type,m>::Contrary() { //补充函数体 //********333******** //********666******** } int main(){ int s1[5]={1,2,3,4,5}; double s2[6]={1.2,2.3,3.4,4.5,5.6,8.4}; Array<int,5> d1(s1,5); Array<double,8> d2(s2,6); int i; d1.Contrary(); d2.Contrary(); cout<<d1.Length()<<' '<<d2.Length()<<endl; for(i=0;i<4;i++) cout<<d1[i]<<", "; cout<<d1[4]<<endl; for(i=0;i<7;i++) cout<<d2[i]<<", "; cout<<d2[7]<<endl; writeToFile(".\\"); //不用考虑此语句的作用 return 0; }
操作题训练(三)
一、基本操作题
//proj1.cpp #include<iostream> using namespace std; class ABC { public: // ERROR **********found********** ABC() {a=0; b=0; c=0;} ABC(int aa, int bb, int cc); void Setab() {++a,++b;} int Sum() {return a+b+c;} private: int a,b; const int c; }; ABC::ABC(int aa, int bb, int cc):c(cc) {a=aa; b=bb;} int main() { ABC x(1,2,3), y(4,5,6); ABC z,*w=&z; w->Setab(); // ERROR **********found********** int s1=x.Sum()+y->Sum(); cout<<s1<<' '; // ERROR **********found********** int s2=s1+w.Sum(); cout<<s2<<endl; return 0; }
二、简单应用题
//proj2.cpp #include <iostream> using namespace std; class Entry { //链接栈的结点 public: Entry* next; // 指向下一个结点的指针 int data; // 结点数据 //**********found********** Entry(Entry* n, int d) : _______________________, data(d) { } }; class Stack { Entry* top; public: Stack() : top(0) { } ~Stack() { while (top != 0) { Entry* tmp = top; //**********found********** top = _______________________; // 让top指向下一个结点 delete tmp; } } void push(int data) // 入栈 //push函数是把入栈数据放入新结点中,并使之成为栈顶结点,原来的结点成为新结点的下一个结点 { //**********found********** top = new Entry(_______________________, data); } int pop() { if (top == 0) return 0; //**********found********** int result = _______________________; // 保存栈顶结点中的数据 top = top->next; return result; } }; int main() { int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Stack s; int i = 0; for (i = 0; i < 10; i++) { cout << a[i] << ' '; s.push(a[i]); } cout << endl; for (i = 0; i < 10; i++) { cout << s.pop() << ' '; } cout << endl; return 0; }
三、综合应用题
//Array.h #include<iostream> #include<string> #include<cstdlib> using namespace std; template<class Type> class Array { //数组类 public: Array(Type b[], int mm):size(mm) { //构造函数 if(size<2) {cout<<"数组长度太小,退出运行!"; exit(1);} a=new Type[size]; for(int i=0; i<size; i++) a[i]=b[i]; } ~Array() {delete []a;} //析构函数 void MinTwo(Type& x1, Type& x2) const; //由x1和x2带回数组a中最小的两个值 int Length() const{ return size;} //返回数组长度 Type operator [](int i)const { //下标运算符重载为成员函数 if(i<0 || i>=size) {cout<<"下标越界!"<<endl; exit(1);} return a[i]; } private: Type *a; int size; }; void writeToFile(string path); //不用考虑此语句的作用
//proj3.cpp #include<iostream> #include "Array.h" using namespace std; //由a和b带回数组a中最小的两个值 template<class Type> void Array<Type>::MinTwo(Type& x1, Type& x2) const { //补充完整函数体的内容 a[0]<=a[1]? (x1=a[0],x2=a[1]): (x1=a[1],x2=a[0]); //********333******** //********666******** } int main() { int s1[8]={29,20,33,12,18,66,25,14}; Array<int> d1(s1,8); int i,a,b; d1.MinTwo(a,b); cout<<d1.Length()<<endl; for(i=0;i<7;i++) cout<<d1[i]<<", "; cout<<d1[7]<<endl; cout<<a<<", "<<b<<endl; writeToFile(".\\"); //不用考虑此语句的作用 return 0; }
操作题训练(四)
一、基本操作题
//proj1.cpp #include <iostream> using namespace std; class AAA { int a[10]; int n; //ERROR **********found********** private: AAA(int aa[], int nn): n(nn) { //ERROR **********found********** for(int i=0; i<n; i++) aa[i]=a[i]; } int Geta(int i) {return a[i];} }; int main() { int a[6]={2,5,8,10,15,20}; AAA x(a,6); int sum=0; //ERROR **********found********** for(int i=0; i<6; i++) sum+=x.a[i]; cout<<"sum="<<sum<<endl; return 0; }
二、简单应用题
//proj2.cpp #include<iostream> using namespace std; class Base { public: Base(int m1,int m2) { mem1=m1; mem2=m2; } int sum(){return mem1+mem2;} private: int mem1,mem2; //基类的数据成员 }; // 派生类Derived从基类Base公有继承 //*************found************** class Derived: _______________ { public: //构造函数声明 Derived(int m1,int m2, int m3); //sum函数定义,要求返回mem1、mem2和mem3之和 //*************found************** int sum(){ return _____________+mem3;} private: int mem3; //派生类本身的数据成员 }; //构造函数的类外定义,要求由m1和m2分别初始化mem1和mem2,由m3初始化mem3 //**********found********** ____________Derived(int m1, int m2, int m3): //**********found********** ____________, mem3(m3){} int main() { Base a(4,6); Derived b(10,15,20); int sum=a.sum()+b.sum(); cout<<"sum="<<sum<<endl; return 0; }
三、综合应用题
//MinString.h #include <iostream> #include <string> #pragma warning (disable:4996) using namespace std; class MiniString { public: MiniString(const char* s) { str=new char[strlen(s)+1]; strcpy(str,s); } ~MiniString() { delete[] str; } MiniString& append(char *p,int n); //将char*数组p的前n个字符添加到现有字符串 char* getStr() const { return str; } friend ostream& operator<<(ostream& o,MiniString& s) //输出字符串str { int len=strlen(s.str); for(int i=0;i<len;i++) o<<s.str[i]; return o; } private: char *str; }; void writeToFile(const char* );
//proj3.cpp #include "MiniString.h" #pragma warning (disable:4996) MiniString& MiniString::append(char *p, int n) { MiniString temp(str); delete[] str; str = new char [strlen(temp.str)+n+1]; //********333******** //********666******** str[strlen(temp.str)+n] = '\0'; return *this; } int main() { MiniString mStr("I am learning C++"); char iStr[]=" and Java"; cout << "Initial strings:\n"; cout << "MiniString: " << mStr << endl; cout << "char*: " << iStr << endl << endl; cout << "Append char* into MiniString:\n"; mStr.append(iStr,7); cout << mStr << endl; writeToFile(".\\"); return 0; }
操作题训练(五)
一、基本操作题
//proj1.cpp #include <iostream> using namespace std; class Clock { public: Clock(unsigned long i = 0); void set(unsigned long i = 0); void print() const; void tick(); // 时间前进一秒 Clock operator++(); private: unsigned long total_sec,seconds,minutes,hours,days; }; Clock::Clock(unsigned long i) : total_sec(i), seconds(i % 60), minutes((i / 60) % 60), hours((i / 3600) % 24), days(i / 86400) {} void Clock::set(unsigned long i) { total_sec = i; seconds = i % 60; minutes = (i / 60) % 60; hours = (i / 3600) % 60; days = i / 86400; } // ERROR **********found********** void Clock::print() { cout << days << " d : " << hours << " h : " << minutes << " m : " << seconds << " s" << endl; } void Clock::tick() { // ERROR **********found********** set(total_sec++); } Clock Clock::operator ++() { tick(); // ERROR **********found********** return this; } int main() { Clock ck(59); cout << "Initial times are" << endl; ck.print(); ++ck; cout << "After one second times are" << endl; ck.print(); return 0; }
二、简单应用题
//proj2.cpp #include <iostream> using namespace std; class Point //定义坐标点类 { public: Point(int xx=0, int yy=0) {x=xx; y=yy;} void PrintP(){cout<<"Point:("<<x<<","<<y<<")";} private: int x,y; //点的横坐标和纵坐标 }; class Circle //定义圆形类 { public: Circle():rr(0){} //无参构造函数 Circle(Point& cen, double rad=0); //带参构造函数声明 double Area(){return rr*rr*3.14159;} //返回圆形的面积 //PrintP函数定义,要求输出圆心坐标和半径 //**********found********** void PrintP(){________________; cout<<rr<<endl;} private: Point cc; //圆心坐标 double rr; //圆形半径 }; //带参构造函数的类外定义,要求由cen和rad分别初始化cc和rr //**********found********** Circle::____________(Point& cen, double rad) //**********found********** ____________ {rr=rad;} int main() { Point x, y(4,5); Circle a(x,3), b(y,6); // 输出两个圆的圆心坐标和半径 a.PrintP(); //**********found********** ____________; cout<<a.Area()<<' '<<b.Area()<<endl; return 0; }
三、综合应用题
//Array.h #include<iostream> #include<cstdlib> using namespace std; template<class Type> class Array { //数组类 Type *a; int size; public: Array(Type b[], int len): size(len) //构造函数 { if(len<1 || len>100) {cout<<"参数值不当!\n"; exit(1);} a=new Type[size]; for(int i=0; i<size; i++) a[i]=b[i]; } int Count(Type x); //统计出数组a中大于等于x的元素个数 int Length() const{ return size; } //返回数组长度 ~Array(){delete []a;} }; void writeToFile(const char *); //不用考虑此语句的作用
//proj3.cpp #include"Array.h" //统计出数组a中大于等于x的元素个数 template<class Type> int Array<Type>::Count(Type x) { //补充函数体 //********333******** //********666******** } void main(){ int s1[8]={20, 13, 36, 45, 32, 16, 38, 60}; double s2[5]={3.2, 4.9, 7.3, 5.4, 8.5}; Array<int> d1(s1,8); Array<double> d2(s2,5); int k1, k2; k1=d1.Count(30); k2=d2.Count(5); cout<<d1.Length()<<' '<<d2.Length()<<endl; cout<<k1<<' '<<k2<<endl; writeToFile(".\\"); //不用考虑此语句的作用 }
操作题训练(六)
一、基本操作题
//proj1.cpp #include<iostream> #include<cmath> using namespace std; class Point{ double x,y; public: // ERROR **********found********** Point(double m=0.0, double n=0.0):m(x), n(y){} friend double distanceBetween(const Point& p1, const Point& p2); }; // ERROR **********found********** double Point::distanceBetween(const Point& p1, const Point& p2){//返回两点之间的距离 double dx=p1.x-p2.x; double dy=p1.y-p2.y; return sqrt(dx*dx+dy*dy); } int main(){ Point f1(0,0), f2(1,1); // ERROR **********found********** cout<<distanceBetween(Point f1, Point f2)<<endl; return 0; }
二、简单应用题
//proj2.cpp #include<iostream> using namespace std; class Switchable{ //具有开、关两种状态的设备 bool is_on; //为 ture 表示“开”,为 false 表示“关” public: Switchable(): is_on(false){} void switchOn(){ is_on=true; } //置为“开”状态 //**********found********** void switchOff(){_________________________________}//置为“关”状态 bool isOn(){ return is_on; } //返回设备状态 //**********found********** virtual const char *getDeviceName()__________; //返回设备名称的纯虚函数 }; class Lamp: public Switchable{ public: //返回设备名称,用于覆盖基类中的纯虚函数 const char *getDeviceName(){ return "Lamp"; } }; class Button{ //按钮 Switchable *device; //按钮控制的设备 public: //**********found********** Button(Switchable &dev): _______________{} //用参数变量的地址初始化device bool isOn(){ return device->isOn(); } //按钮状态 void push(){ //按一下按钮改变状态 if(isOn()) device->switchOff(); //**********found********** else ___________________________ } }; int main(){ Lamp lamp; Button button(lamp); cout<<"灯的状态:"<<(lamp.isOn()? "开" : "关")<<endl; cout<<"按钮的状态:"<<(button.isOn()? "开" : "关")<<endl; button.push(); //按一下按钮 cout<<"灯的状态:"<<(lamp.isOn()? "开" : "关")<<endl; cout<<"按钮的状态:"<<(button.isOn()? "开" : "关")<<endl; return 0; }
三、综合应用题
//MinString.h #include <iostream> #include <string> #pragma warning (disable:4996) using namespace std; class MiniString { public: MiniString(const char* s) { str = new char[strlen(s)+1]; strcpy(str,s); } ~MiniString() { delete[] str; } //删除从pos处开始的n个字符,然后在pos处插入字符串p MiniString& replace(int pos,int n,char *p); char* getStr() const { return str; } friend ostream& operator<<(ostream& o,MiniString& s); //输出字符串str private: char *str; }; void writeToFile(const char *);
//proj3.cpp #include "MiniString.h" #pragma warning (disable:4996) ostream& operator<<(ostream& o,MiniString& s) { int len=strlen(s.str); for(int i=0;i<len;i++) cout<<s.str[i]; return o; } MiniString& MiniString::replace(int pos, int n, char *p ) { MiniString temp(str); //创建一个副本以保存前字符串信息 delete[] str; //释放字符串数组 int lt=strlen(temp.str),lp=strlen(p); int len=lt-n+lp+1; //计算存放结果字符串所需空间大小 str=new char[len]; //申请存放结果所需字符数组 //分别把temp.str中的前pos个字符和p中的lp个字符复制到str中 //********333******** //********666******** //把temp.str后面剩余的字符串复制到str中 for(int k=pos+n; k<lt; k++) str[pos+lp++]=temp.str[k]; str[len-1]='\0'; return *this; } int main() { MiniString mStr("String handling C++ style."); char iStr[]="STL Power"; cout << "Replace char* into MiniString:\n"; mStr.replace(7, 8, iStr); cout << mStr << endl; writeToFile(""); return 0; }