第3章 类与对象习题 参考答案 下载本文

内容发布更新时间 : 2024/6/2 0:55:09星期一 下面是文章的全部内容请认真阅读。

第3章 类与对象 习题参考答案

一、选择题(共30分,每题1分)

1 C 11 A 21 C

2 B 12 C 22 D 3 C 13 B 23 B 4 D 14 A 24 B 5 D 15 A 25 A 6 B 16 D 26 D 7 D 17 B 27 B 8 A 18 C 28 B 9 D 19 C 29 A 10 C 20 D 30 A 二、填空题(共18分,每题1分)

1. 不能

2. 将对象A复制给对象B

3. (1) public (2) 成员函数 4. 实例

5. 复制( 拷贝)

6. 类(test ) ~test() 7. 对象 类

8. 重载 返回值 参数 9.默认(无参) 10. ->

11. 构造函数

12.函数返回类型 类名::成员函数名(参数表); 13. 常对象 14. 对象名 15. 析构函数

三、改错题(共12分,每题2分)

1. void Point(int a)------------ Point(int a)

cout<

2. 答案:int i, int j-----------int i, int j=0 //注:只要有一个int类型的数据就行。 分析:调用时,既有一个参数,也有两个参数,且没有重载,所以参数需要带默认值。

3. 答案:swap(&a,&b); ------------swap(a, b);

分析函数的形参是变量的引用,调用时的实参应该是地址。

4. #include class one

{ int a1,a2; public:

one(int x1=0, int x2=0) //修改1:构造函数的函数体没有 {a1=x1;a2=x2;} show() //修改2 定义成员函数 {cout<

void main()

{ one data(2,3);

data.show(); //修改3:用对象调用成员函数 }

5. ABC(int aa)a(aa){} ------------ABC(int aa):a(aa){} 分析:构造函数的初始化列表格式错误。

6. 答案:cout<

四、看程序写结果(共15分,每题3分)

1.

输出:

Constructing normally

Constructing with a number:59 Display a number:0 Display a number:59 Destructing Destructing

2.s=150

3.62

[解析]x是普通对象,调用普通的print函数;而y常对象,调用常成员函数。

4.答案:108

[解析]p指向对象x2,x2.getA()+5该值为8 即x2.a=8;10+x1.getA()为10,x1.a=10。

5. 38

五、编程题(共25分)

1. 某商店经销一种货物,货物成箱购进,成箱卖出,购进和卖出时以重量为单位,各箱的

重量不一样,因此,商店需要记下目前库存货物的总量,要求把商店货物购进和卖出的情况模拟出来。 #include using namespace std; class Goods { double weight; static double totalweight; public: Goods(double w) { weight=w; totalweight+=weight; } ~Goods(){ totalweight-=weight; } static double getTotalWeight(){ return totalweight; } };

double Goods::totalweight=0; void main() { Goods *g1,*g2; g1=new Goods(10.0); //买进货物,增加总重量 g2=new Goods(20.0); cout<<\总重量\ delete g1; cout<<\卖掉一个以后的总重量\ delete g2; cout<<\再卖掉一个后的总重量\}

2. 声明一个长方形Box,该类有长(length)、宽(width)、高(height) 三个数据成员,类中有获取及修改、宽、高的函数,以及计算长方形表面积和体积的函数,声明默认的构造函数和带有3个参数的构造函数。在main函数中进行测试。 #include //包含头文件命令 using namespace std; //使用名字空间std class Box {public: Box(){ length=1; width=1; height=1; } //默认构造函数 Box(int length, int width, int height): length(length), width(width), height(height){}