logo资料库

李爱华、程磊_面向对象程序设计课后答案.doc

第1页 / 共28页
第2页 / 共28页
第3页 / 共28页
第4页 / 共28页
第5页 / 共28页
第6页 / 共28页
第7页 / 共28页
第8页 / 共28页
资料共28页,剩余部分请下载后查看
第二章 2-4 #include 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 < 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<<"正数有:"< //#include 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 { } catch( string) { } catch(int) { continue; } checkagescore(name,age); cout<<"exception :name is exit"<
第三章 (7)B (8)C (9)C 3-1 (1)A (2)C (3)B (4)C (5)C (6)B 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<
第四章 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 //#include using namespace std; class Ctest { private: public: int x; const int y1; 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 略 4-10 #include #include class Student int number; char name[20]; { } public: Student(int i=0,char *s="\0") { number=i; strcpy(name,s); //构造学生对象
void Print() { //输出结果 cout<<"Number:"<st2.number; //返回成员 number 的比较结果 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])) if(!greaterthan(st[i],st[min])) max = i; min = i; } cout<<"最大成绩:"< #include using namespace std; class Book { char *name;
分享到:
收藏