李爱华、程磊_面向对象程序设计课后答案(完整版)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第二章2-4
#include <iostream>
using namespace std;
Add(int a,int b);
int main()
{
int x,y,sum;
cout<<"please input x and y:";
cin>>x>>y;
sum = add(x,y);
cout <<x<<"+"<<y<<"="<<sum<<endl;
}
Add(int a,int b)
{
return a+b;
}
2-5
(1)this is a C++ program.
(2)
x=50.6 y=10 z=A
x=216.34 y=10 z=A
x=216.34 y=2 z=A
x=216.34 y=2 z=E
(3)
x y z
500 1000 0
500 1500 1500
500 200 1500
2-6
#include <iostream>
using namespace std;
int main()
{
int *p,*init;
int countp=0;
int countn=0;
p = new int[20];
init = p;
for(int i=0;i<20;i++)
{
cin>>*p;
p++;
}
p = p-20;
for( i=0;i<20;i++)
{
if(*p>0) countp++;
if(*p<0) countn++;
cout<<*p<<" ";
p++;
}
cout<<"正数有:"<<countp<<endl; cout<<"负数有:"<<countn<<endl;
p = init;
delete[] p;
return 0;}
2-7不做要求
#include <iostream>
//#include <string>
using namespace std;
void checkagescore(string name,int age) {
if (name == "exit") throw name;
if(age<0||age>50)
throw age;
int main()
{
string name;
int age;
for(int i=0 ;i<5 ;i++ )
{
cin.ignore ();
getline(cin,name );
cin>>age ;
try
{
checkagescore(name,age);
}
catch( string)
{
cout<<"exception :name is exit"<<endl;
continue;
}
catch(int)
{
cout<<"exception :age is not proper"<<endl;
continue;
}
cout<<"name:"<<name<<" age :"<<age<<endl;
}
return 0;
}
第三章
3-1
(1)A (2)C (3)B (4)C (5)C
(6)B (7)B (8)C (9)C
3-7
(1)
main()函数中
p1.age = 30;语句是错误的。

age 是类的私有成员
(2)
构造函数应当给常数据成员和引用成员初始化,将构造函数改为:A(int a1,int b1):a(a1),b(b1){}

A(int a1 ):a(a1),b(a){}再将main中的A a(1,2); 改为A a(1);
(3)
(1)在Test 类中添加语句:
void print();
void Print(){
cout<<x<<"-"<<y<<"="<<x-y<<endl;
}
改为
void Test::Print(){
cout<<x<<"-"<<y<<"="<<x-y<<endl;
}
main函数中
Init(38,15);改为:
A.Init(38,15);
Print();改为:
A.Print();
3-8
(1)
Constructing A
Constructing B
Destructing B
Destructing A
(2)
double a,double b
point & p
p.x
3-9
class box
{
int len1,len2,len3;
public:
box(int l1,int l2,int l3){len1 = l1;len2 = l2; len3 = l3;} long volumn(){return len1*len2*len3;}
};
3-10
class Test{
int m1,m2;
public:
void Init(int a,int b){m1 = a;m2 = b;}
void Pring(){cout<<m1<<" "<<m2<<endl;}
};
3-11

3-12
}
第四章
4-6
(1)D (2)D (3)D (4)D (5)B
(6)D
4-7
(1)
static int count = 0;这样初始化静态成员值是不对的将其改为static int count;
在类外,main函数前加
int Sample::count = 0;
(2)
#include <iostream>
//#include <cstdlib>
using namespace std;
class Ctest
{
private:
int x; const int y1;
public:
const int y2;
Ctest(int i1,int i2):y1(i1),y2(i2)
{
y1 =10;//y1 为常量不能赋值
x = y1;
}
int readme() const;
};
int Ctest::readme ()const
{
int i;
i = x;
x++; //常函数内不能改变成员值
return x;
}
int main()
{
Ctest c(2,8);
int i = c.y2;
c.y2 = i;//y2为常量,不能改值
i = c.y1;//y1私有,类外不能访问
return 0;
}
将出错语句全部注释
4-8
(1)
题中印刷错误,将class C构造函数改为:
C()
{cout<<"constructor C:";}
运行结果为:
constructor A
constructor B
constructor C
(2)
40
(3)
3
4
3
4-9#include<iostream.h>
#include<stdio.h>
class Date
{
int year;
int month;
int day;
public:
Date(int y,int m,int d)
{
year=y;month=m;day=d;
}
void disp()
{
cout<<year<<" "<<month<<" "<<day<<endl;
}
friend int count_day(Date &d,int k);
friend int l(int year);
friend int h(Date &d1,Date &d2);
};
int count_day(Date &d,int k)
{
static int day_tab[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}};
// 使用二维数组存放各月天数,第一行对应非闰年,第二行对应闰年
int j,i,s;
if(l(d.year))
j=1;//闰年,取1
else j=0;//非闰年,取0
if(k)//K非0时
{
s=d.day;
for(i=1;i<d.month;i++)//d.month为输入的月份
s+=day_tab[j][i-1];
}
else//K为0时
{
s=day_tab[j][d.month]-d.day;
for(i=d.month+1; i<=12; i++)
s+=day_tab[j][i-1];
}
return s;//S为相差的天数
}
int l(int year)
{
if(year%4==0&&year%100!=0||year%400==0) // 是闰年
return 1;
else // 不是闰年
return 0;
}
int h(Date &d1,Date &d2)
{
int days,day1,day2,y;
if(d1.year<d2.year)//第一个日期年份小于第二个日期年份
{
days=count_day(d1,0);
for(y=d1.year+1;y<d2.year;y++)
if(l(y))//闰年
days+=366L;
else//非闰年
days+=365L;
days+=count_day(d2,1);
}
else if(d1.year==d2.year)
{
day1=count_day(d1,1);
day2=count_day(d2,1);
days=day2-day1;
}
else
days=-1;
return days;
}
void main()
{ int year1,year2,month1,month2,day1,day2;
cout<<"输入日期1"<<endl;
cin>>year1>>month1>>day1;
cout<<"输入日期2"<<endl;
cin>>year2>>month2>>day2;
Date d1( year1, month1, day1),d2( year2, month2, day2);
int ds=h(d1,d2);
{
cout<<"输出结果:"<<endl;
}
if(ds>=0)
{
d1.disp(); printf("与");
d2.disp(); printf("之间有%d天\n\n",ds);
}
else//第一个日期小于第二个日期
cout<<"时间错误!"<<endl;
}
4-10
#include<iostream.h>
#include<string.h>
class Student
{
int number;
char name[20];
public:
Student(int i=0,char *s="\0") //构造学生对象
{ number=i;
strcpy(name,s);
}
void Print() //输出结果
{ cout<<"Number:"<<number<<endl;
cout<<"Name:"<<name<<endl;
}
friend bool greaterthan(Student &st1,Student &st2);
};
bool greaterthan(Student &st1,Student &st2)
{
return st1.number>st2.number; //返回成员number的比较结果
}
int main()
{
Student
st[5]={Student(65,"Li"),Student(78,"Zhang"),Student(80,"wang"),Student(92,"zhao"), Student(50,"zhen")};
int max = 0;
int min = 0;
for(int i=1;i<5;i++)
{ if(!greaterthan(st[max],st[i]))
max = i;
if(!greaterthan(st[i],st[min]))
min = i;
}
cout<<"最大成绩:"<<endl;
st[max].Print ();
cout<<"最小成绩:"<<endl;
st[min].Print ();
return 0;
}
4-11
#include <iostream>
#include <string>
using namespace std;
class Book
{
char *name;
char*author;
int sale;
public:
Book()
{ name = '\0';
author = '\0';
sale = -1;
}
Book(char* a ,char* b,int c)
{
name = new char[strlen(a)+1];
strcpy(name,a);
author = new char[strlen(b)+1];
strcpy(author,b);
sale = c;
}
void print()
{cout<<"autor "<<author<<endl;
cout<<"name "<<name<<endl;
cout<<"price "<<sale<<endl;
}
~Book()
{
if(!name ) delete[] name;
if(!author)delete[] author;
}
};
int main()
{
Book b1("c++","li ai hua",12);
Book b2;
return 0;
}
第五章5-8
改错题答案不唯一
(1) class DC {
int x;
public:
DC(){x =100;}
};
(2)编译无错,但逻辑错误,可改为:
class BC
{
protected:
int x;
public:
BC(int i=0){x = i}
};
class DC:private BC
{
public:
DC(int i):BC(i){}
};
(3)将DC构造函数改为:
DC(int i):BC(i){y = 0;}
5-9
(1) base class
(2) (10,5)
(3,9-18,33)
(13,19)
(13,19-18,33)
(13,19)
5-10
#include <iostream>
using namespace std;
class Shape
{
int x,y;
public:
Shape(int ix,int iy){x = ix; y = iy;}
virtual void show(){cout<<"pos: "<<x<<' '<<y<<endl;}
};
class Circle :public Shape
{
int radius;
public:
Circle(int ix,int iy,int r):Shape(ix,iy),radius(r){}
void show() {Shape::show ();
cout<<"circle: "<<radius<<endl;}
};
class Rect :public Shape
{
int width,higth;
public:
Rect(int ix,int iy,int iw,int ih):Shape(ix,iy),width(iw),higth(ih){} void show() {Shape::show ();
cout<<"width and higth: "<<width<<' '<<higth<<endl;} };
int main()
{
Shape s1(1,1);
Rect r1(2,2,8,8);
Circle c1(3,3,9);
r1.show ();
c1.show();
return 0;
}
5-11
#include<iostream.h>
class vehicle // 定义汽车类
{
protected:
int date; // 年份
float price; //价格
public:
vehicle(int date,float price);
int get_date();
float get_price();
float date_load();
void show();
};
class car:public vehicle // 定义小车类
{
int passenger_load; // 载人数
public:
car(int date,float price,int passengers=4);
int get_passengers();
void show();
};
class truck:public vehicle // 定义卡车类
{
float payload; // 载重量
public:
truck(int date,float price,float max_load=24000.00); float efficiency();
void show();
};
vehicle::vehicle(int date,float price)
{
vehicle::date=date;
vehicle::price=price;
}
int vehicle::get_date()
{
return date;
}
float vehicle::get_price()
{
return price;
}
void vehicle::show()
{
cout << "年份:" << date << "年" << endl;
cout << "价格:" << price << "元" << endl;
}
car::car(int date, float price,
int passengers) :vehicle (date, price)
{
passenger_load=passengers;
}
int car::get_passengers ()
{
return passenger_load;
}
void car::show()
{
cout <<" 车型:小车" << endl;
vehicle::show();
cout << "载人:" << passenger_load << "人" << endl;
cout << endl;
}
truck:: truck(int date, float price,float max_load):vehicle(date,price) {
payload=max_load;
}
float truck::efficiency()
{
return payload;
}
void truck::show()
{
cout <<"车型:卡车" << endl;
vehicle:: show ();
cout << "载重:" << efficiency() << endl;
cout << endl;
}
void main ()
{
car car1(2001,2000,5);
truck tru1(2002,8000,340000);
cout << "输出结果" << endl;
car1. show ();
tru1. show ();
}
第六章
6-4
d=3
D::fun();
6-5
C::print(),cinfo=2
C::print(),cinfo=2
D::print(),dinfo=4
B类不能定义对象,否则编译通不过,因为B未定义基类A中的虚函数print(),它也是个虚基类。

6-6
#include <iostream>
using namespace std;
class Mammal
{
public:
virtual void Speak()
{cout<<"in Mammal"<<endl;}
};
class Dog:public Mammal
{
public:
void Speak()
{cout<<"dog bark"<<endl;}
};
int main()
{
Dog dog;
Mammal *pM;
pM = &dog;
pM->Speak ();
return 0;
}
运行结果:
dog bark
6-7
#include <iostream>
using namespace std;
class BaseClass
{
public:
virtual ~BaseClass()
{cout<<"destruct Base"<<endl;}
};
class Derived:public BaseClass
{
public:
~Derived()
{
cout<<"destruct derived"<<endl;
}
};
int main()
{
BaseClass *pbase;
pbase = new Derived;
delete pbase;
}
结果将不能正常执行子类析构
6-8 #include <iostream>
using namespace std;
class Shape
{
public:
virtual double Area() = 0;
};
class Circle :public Shape
{
double radius;
public:
Circle(double r):radius(r){}
double Area() {return 3.14*radius*radius;} };
class Square :public Shape
{
double radius;
public:
Square(double r):radius(r){}
double Area() {return 6*radius*radius;}
};
class Rectangle :public Shape
{
double width,radius;
public:
Rectangle(double w,double r):radius(r){width=w;}
double Area() {return width*radius;}
};
class Trapezoid :public Shape
{
double height,radius,length;
public:
Trapezoid(double h,double r,double l):radius(r){height=h;length=l;} double Area() {return height*(radius+length)/2;}
};
class Triangle :public Shape
{
double height,radius;
public:
Triangle(double h,double r):radius(r){height=h;}
double Area() {return height*radius/2;}
};
int main()
{
double AreaSum= 0;
Shape * pS[6];
pS[1] = new Circle(1);
pS[2] = new Square(2);
pS[3] = new Rectangle(1,2);
pS[4] = new Trapezoid(4,2,5);
pS[5] = new Triangle(4,2);
AreaSum += pS[1]->Area();
AreaSum += pS[2]->Area();
AreaSum += pS[3]->Area();
AreaSum += pS[4]->Area();
AreaSum += pS[5]->Area();
cout<<"总面积是:"<<AreaSum<<endl;
cout<<"各三维图形面积如下:"<<endl;
cout<<"圆形:"<<pS[1]->Area()<<endl;
cout<<"正方形:"<<pS[2]->Area()<<endl;
cout<<"长方形:"<<pS[3]->Area()<<endl;
cout<<"梯形:"<<pS[4]->Area()<<endl;
cout<<"三角形:"<<pS[5]->Area()<<endl;
return 0;
}
6-9
#include <iostream>
using namespace std;
class Student
{
public:
virtual void show() = 0;
};
class Junior :public Student
{
public:
void show(){cout<<"this would be info for junior students"<<endl;} };
class Senior :public Student
{
public:
void show(){cout<<"this would be info for Senior students"<<endl;} };
int main()
{
Student *pstu;
pstu = new Junior;
pstu->show ();
pstu = new Senior; pstu->show (); return 0;
}
第七章7-1
#include <iostream>
#include <string>
using namespace std;
class vector
{
int x,y;
public:
vector(int ix=0,int iy=0){x =ix;y = iy;}
vector operator+(vector& v1)
{
return vector(x+v1.x,y+v1.y);
}
vector& operator+=(vector& v1)
{
x +=v1.x;
y +=v1.y;
return *this;
}
void show()
{
cout<<'('<<x<<','<<y<<')'<<endl;
}
};
int main()
{
vector v1(1,2),v2(3,4),v3;
v3 = v1+v2;
v1+=v2;
v3.show();
v1.show();
return 0;
}
7-2
#include <iostream.h>
class Complex
{
private:
double real,image;
public:
Complex(double x=0.0,double y=0.0)
{ real =x; image =y; }
bool operator !=(const Complex &c);
Complex operator -(const Complex &c);
bool operator ==(const Complex &c);
Complex operator -();
Complex &operator +=(const Complex &c);
void Print();
};
void Complex::Print()
{
cout<<real<<" + "<<image<<"i"<<endl;
}
Complex Complex ::operator -(const Complex &c) {
Complex temp(real-c.real,image-c.image);
return temp;
}
bool Complex ::operator ==(const Complex &c)
{
return (real==c.real && image==c.image);
}
bool Complex::operator !=(const Complex &c)
{
return (real!=c.real || image!=c.image);
}
Complex Complex ::operator -()
{
return Complex(-real,-image);
}
Complex &Complex ::operator +=(const Complex &c) {
real+=c.real;
image+=c.image;
return *this;
}
int main()
{
Complex c1(2,7),c2(4,2),c3;
c3=c1-c2;
c3.Print();
if(c3==c1)cout<<"c3 equals to c1"<<endl;
else cout<<"c3 doesn?ˉt equale to c1"<<endl;
c3=-c2;
c3.Print();
c3+=c2;
c3.Print();
if(c3 != c1) cout<<"c3!=c1"<<endl;
return 0;
}
7-3
#include <iostream>
using namespace std;
bool rn(int y)
{
bool flag = 0;
if(y%400==0 || y%4 ==0&&y%100!=0)
flag = 1;
return flag;
}
class Date
{ private:
int month, day, year;
public:
Date(int m, int d, int y);
Date& operator+(int days);
void showDate();
};
Date::Date(int y, int m, int d)
{ if (m>0 && m<13)
month=m;
if (d>0 && d<32)
day=d;
if (y>0 && y<3000)
year=y;
}
Date& Date::operator+(int days)
{
int i;
for(i = days;i>0;)
{
int diff ;
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: diff = 31 -day;break;
case 4:
case 6:
case 9:
case 11: diff = 30 -day;break;
case 2:if (rn(year))diff = 29 - day;
else diff = 28 -day;
break;
}
if(i>diff)
{
i-= diff+1;
day = 1;
month++;
if(month>12)
{
year++;
month = 1;
}
}
else
{
day+= i;
break;}
}
return *this;
}
void Date::showDate()
{
cout<<year<<"."<<month<<"."<<day<<endl; }
int main()
{
Date obj(1996,1,1);
obj.showDate ();
obj = obj+59;
obj.showDate();
return 0;
}
7-4 以+,=为例
#include<iostream>
#include<string.h>
using namespace std;
class String
{
char *sbuf;
int length;
public:
String()
{
length=0;
sbuf=new char;
sbuf[0]='\0';
}
String(char *s) //用字符串初始化{
length=strlen(s);
sbuf=new char[length+1];
strcpy(sbuf,s);
}
String (String& str)
{
length=str.length ;
sbuf=new char[length+1];
strcpy(sbuf,str.sbuf );
}
~String()
{
delete[] sbuf;
}
String & operator =(String& str)
{
if(sbuf == str.sbuf )
return *this;
else
{
sbuf = new char[str.length +1];
strcpy(sbuf,str.sbuf );
return *this;
}
}
String operator +(String& str)//此函数需配合拷贝构造函数
{
String st;
st.length = length + str.length ;
st.sbuf = new char[st.length+1 ];
st.sbuf [0] = '\0';
strcpy(st.sbuf,sbuf);
strcat(st.sbuf,str.sbuf );
return st;
}
char & operator[](int i)
{
if(i<0||i>=length) //对下标进行检查,超出范围则报错退出程序{
cout<<"下标越界错误!"<<endl;
exit(0);
}
return sbuf[i];
}
void Show()
{
cout<<sbuf<<endl;
}
};
int main()
{
String s1("hello");
String s2("world"),s3 ;
s3 = s1+s2; //
s3.Show ();
return 0;
}
7-6
第八章8-1
(1)template<typename T>
T fun(T a)
{....}
(2) template<typename T>
T test(T a)
{....}
(3) template<typename T>
class Array
{
public:
void fun();
}
template<typename T>
void Array<T>::fun()
{.....}
(4)Array<int> a1,a2,a3;
8-4
#include<iostream>
using namespace std;
template <typename T>
T max(T a,T b,T c)
{
T temp;
temp=a>b?a:b;
temp=temp>c?temp:c;
return temp;
}
int main()
{
cout<<max(11,29,22)<<endl;
cout<<max(3.14f,28.3f,6.7f)<<endl;
cout<<max('c','b','a')<<endl;
return 0;
}
8-5及8-6
#include< iostream>
#include<string>
using namespace std;
template <typename T >
void sort_bubble(T arr[],int n)
{
for(int i=0; i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
if( arr[j]<arr[j+1])
{T temp; temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp;} }
}
class student
{
int num;
string name;
public:
student(int n=0,string ns="")
{
num = n;
name = ns;
}
bool operator<(student s1)
{
return (num<s1.num );
}
void print()
{
cout<<num<<" "<<name;
cout<<endl;
}
};
int main()
{
int arri[]={2,4,1,43,56,78};
float arrf[]={1.2f,4.5f,21.4f,98.9f};
sort_bubble(arri,6);
sort_bubble(arrf,4);
for(int i=0;i<6;i++)
cout<<arri[i]<<" ";
cout<<endl;
student stuarr[] = {student(3,"liqing"),student(1,"liou"),student(4,"cha")};
sort_bubble(stuarr,3);
for(i=0;i<3;i++)
stuarr[i].print();
for( i=0;i<4;i++)
cout<<arrf[i]<<" ";
cout<<endl;
return 0;}
…其他略
第十章10-1
(1)B (2)B (3)A (4)C (5)A
10-2
10-3
#include <iostream>
#include<fstream>
using namespace std;
int main()
{
fstream fs;
ofstream fsc("d:\\lqing01.txt");
fs.open("D:\\lin.txt",ios::in|ios::out );
if(!fs)
{
cout<<"cant open file"<<endl;
exit(-1);
}
for(int i=1;i<51;i++)
{
fs.put(65);
if(i%5 == 0 && i!=50)
fs.put('\n');
}
fs.put(-1);
char ch;
int count = 1;
cout<< count <<" ";
// fsc.put(count+'0');
fsc<<count;
fsc.put(' ' );
fs.seekg(0,ios::beg);
fs.get(ch);
while(ch!=-1)
{
cout<<" "<<ch;
fsc.put(ch);
if(ch =='\n')
{
count++;
cout<<count <<" ";
// fsc.put(count+'0');
fsc<<count;
fsc.put(' ');
}
fs.get(ch);
}
fs.close();
fsc.close ();
//读回来看看
cout<<endl;
cout<<endl;
cout<< endl<<endl;
ifstream fr("d:\\lqing01.txt");
if(!fr)
{
cout<<"failed to open lqing01.txt"<<endl;
exit(-1);
}
char cha[20];
while( fr.getline(cha,20))
cout<<cha<<endl;
return 0;
}
//将文件lin 加行号写入lqing01_txt
10-4
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream of("d:\\01.txt",ios::app);//文件01.txt应已存在ifstream ifs("d:\\02.txt");
if(!of || !ifs)
{
cout<<"cant open file";
exit(-1);
}
char ch;
while(ifs>>ch)
{
of<<ch;
}
of.close ();
ifs.close();
return 0;
}。

相关文档
最新文档