第二章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;。