![]() ![]() |
|||||||||||||
C++练习题及解答----练习题(二)参考答案 | |||||||||||||
作者:佚名 文章来源:不详 点击数 更新时间:2008/4/18 16:08:09 文章录入:杜斌 责任编辑:杜斌 | |||||||||||||
|
|||||||||||||
一,[理解问答题] 请回答下面有模板的定义问题: 1.下列模板的定义是否合法的?若为非法的,请简单扼要说明理由。 (1) 非法的,两次声明不一样 (2) 合法的 (3) 非法的,两个类型参数的名字不能相同 (4) 非法的,参数U没有类型说明 (5) 合法的 2.关于类List的如下定义中有若干错误,请指出其所在行号并改正 (但不求补充实现成员函数)。 1 template <class elemType> class ListItem; 2 3 template<class elemType> class List 4 { 5 public: 6 List (): front(NULL), end(NULL){} //有错 7 List (const List &); //有错 8 ~List(); 9 void insert(ListItem<elemType> *ptr, elemType value);//有错 10 int remove(elemType value); //有错 11 int size( ) { return size; } 12 private: 13 ListItem<elemType> *front; //有错 14 ListItem<elemType> *end; //有错,以上错均已改正 15 };
二,[理解问答题] 问题1. 答:程序的输出结果为: Size of val_array = 10 The values of val_array before calling inv(): 0 1 2 3 4 5 6 7 8 9 The result of val_array after calling inv(): 0 -1 -2 -3 -4 -5 -6 -7 -8 -9
问题2.答:
问题3.答:该函数实现有以下错误: (1) 函数的参数x为const参数,不能在函数体中被改变 (2) 在函数中应该创建一个临时对象,这个对象的内容由参数x的内容运算而来 (3) 函数返回的应是临时对象,而不是参数
正确的函数实现为: template<class T> val_ary<T> inv(const val_ary<T>& x) { INTARY ret_array(x); //利用拷贝构造函数构造临时对象 for (int i = 0; i < x.size(); i++) ret_array *= -1; //符号取反 return ret_array; //返回临时对象 }
或者
template<class T> val_ary<T> inv(const val_ary<T>& x) { INTARY ret_array(x.size()); //构造一个与x长度相同的对象 for (int i = 0; i < x.size(); i++) ret_array = x * (-1);//符号取反 return ret_array; //返回临时对象 }
问题4.答:重载了取数组下标的运算符’[]’
三,[理解问答题] 答:输出结果为: class Cla_ Base: Hello! class Cla_ Sub: 2000 //动态联编和函数重载的结果应访问Cla_Sub Disply in class Cla_Base without parameter! class Cla_ Sub: Hi! Disply in class Cla_Sub without parameter! There are 6 objects // Sub1, Cla_Sub[5]共建6个对象 There are 1 objects // 还有一个对象Sub1 |
|||||||||||||
![]() ![]() |