当前位置:首页 > 面向对象程序设计(C++)自我测试练习参考答案
#include \#define N 3 class Student { float score; static float total; static float count; public: void scoretotal(float s) { score = s; total += score; count++; }
static float sum() { return total; } static float average() {
return total/count; } };
float Student::count =0; float Student::total =0; void main() {
Student a[N]; float fScore; for(int i=0;i
第8章 多态性和虚函数
一、单选题
1.`关于动态联编的描述中,( B )是错误的。 A. 动态联编是以虚函数为基础的。
B.动态联编是在编译时确定所调用函数的。
C.动态联编是通过对象的指针或对象引用调用虚函数来实现的。 D.动态联编是在运行时确定所调用函数的。 2.关于虚函数的描述中,( D )是正确的。 A.虚函数是一个非成员函数。
B.虚函数是一个static类型的成员函数。
C.派生类的虚函数与基类的虚函数具有不同的参数个数和类型。 D.基类中说明了基函数后,派生类中与其对应的虚函数前面可以不加virtual关键字。 3.关于纯虚函数和抽象类的描述中,( C )是错误的。 A.纯虚函数是一种特殊的虚函数,它没有具体的实现。 B.具有纯虚函数的类是抽象类。 C.一个基类中说明有纯虚函数,该类的派生类一定不是抽象类。 D.抽象类只能作为基类来使用,其纯虚函数的实现由派生类给出。 4.包含一个或多个纯虚函数的类称为( A )。
A.抽象类 B. 虚拟类 C. friend类 D. protected类 5. 编译时多态性通过使用( B )获得。
A. 继承 B. 虚函数 C. 重灾函数 D. 析构函数 6.在下列运算符中,不能重载的是( C )。
A. <= B. >> C. :: D. &=
二、填空题
1.在C++中,有一种不能定义对象的类,这种类只能被继承,称为 抽象类 ,定义该类至少具有一个 纯虚函数 。 2.阅读分析以下程序
#include \class A {
int a; public:
A(int i=0){a=i;}
virtual void show() //A行 { cout<<\};
class B: public A {
int d;
void show()
{ cout<<\public:
B(int i=0,int j=0):A(i) { d=j;}
void fun(A &obj) };
{ void fun(A *obj)
obj.show (); {
} obj->show ();
void main() { B *p = new B(5,8); fun(*p); delete p; }
}
void main() {
B *p = new B(5,8); fun(p); delete p; }
(1) 程序运行结果是 B::show() called.8 ;若将A行的关键字virtual删除,则运行结果为: A::show() called.5 。
(2) 若将fun()和main()修改为框图中对应的函数,则若A行有virtual时,运行结果为: B::show() called.8 ;则若A行无virtual时,运行结果为: A::show() called.5 。
3. 双目运算符重载为类的成员函数时,重载函数有 1 个参数;双目运算符重载为类的友元函数时,重载函数有 2 个参数。
三、编程题
1. 定义一个类Base,该类含有虚成员函数display(),然后定义它的两个派生类FirstD和SecondD,这两个派生类中均含有公有成员函数display()。在主程序中,定义指向基类Base的指针变量ptr,并分别定义Base、FirstD、SecondD的对象b1、f1、s1,让ptr分别指向b1、f1、s1的起始地址,然后执行这些对象的成员函数display()。
#include
int x,y; public:
Base( int x1,int y1) {
x=x1;y=y1; }
virtual int display() //虚函数 { cout<<\点的面积为0\ return 0; } };
class FirstD: public Base {
int l,w; public:
FirstD( int x1,int y1,int l1,int w1): Base (x1,y1) {
l=l1; w=w1; }
int display() //重新改写虚函数 {
return l*w;
} };
class SecondD: public Base {
int l,w; public:
SecondD( int x1,int y1,int l1,int w1): Base (x1,y1) {
l=l1; w=w1; }
int display() //重新改写虚函数 {
return l*w; } };
void main( ) {
Base *ptr; Base b1(1,2);
FirstD f1(1,2,3,4); SecondD s1(5,6,7,8); ptr = &b1;
cout< cout< cout< 2. 按下列要求编写程序: (1)定义一个类Shapes,类中含有protected成员变量x、y、z,分别为矩形的长、宽、圆的半径值。定义成员函数dShapes(d,w),用来设置成员变量x、y的初值;定义成员函数rShapes(r1),用来设置成员变量z的初值;定义纯虚函数display()。 (2)定义类Shapes的派生类Square和Circle,其成员函数display用来计算矩形和圆的面积、周长。 (3)在主程序中定义一个指针数组ptr,指向类Shapes的对象;定义s1为类Square的对象,c1为类Circle的对象。ptr对象指针数组的第0个元素存放对象s1的地址,第1 个元素存放c1的地址。用对象指针计算并输出矩形、圆的面积和周长。 #include protected: int x,y,z; public: void dShapes( int d,int w)
共分享92篇相关文档