面向对象程序设计(C++)自我测试练习参考答案 联系客服

发布时间 : 星期二 文章面向对象程序设计(C++)自我测试练习参考答案更新完毕开始阅读6d699ec07cd184254a353549

{

x=d;y=w; }

void rShapes( int r) {

z=r; }

virtual void display() =0; //纯虚拟函数 };

class Square: public Shapes {

public:

void display() //重新改写虚函数 {

cout<< x*y << endl; cout<< 2*x*y<< endl; } };

class Circle: public Shapes {

public:

void display() //重新改写虚函数 {

cout<< 3.14*z*z << endl; cout<< 2*3.14*z << endl; } };

void main( ) {

Shapes *ptr[2]; Square s1; Circle c1; ptr[0] = &s1; ptr[1] = &c1;

ptr[0]->dShapes (2,3); ptr[1]->rShapes (4); ptr[0]->display (); ptr[1]->display (); }

3. 声明一个哺乳动物类Mammal,再由此派生出狗类Dog,二者都定义Speak()成员函数,基类中定义为虚函数。声明Dog类的一个对象,调用Speak()函数,观察运行结果。 #include \class Mammal

{

public:

virtual void Speak() {

cout<<\被调用了。\ } };

class Dog: public Mammal {

public:

virtual void Speak() {

cout<<\被调用了。\ } };

void main() {

Dog obj; obj.Speak (); }

4. 编写一个密码类,其中包含一个str密码字符串私有成员数据,以及一个“==”运算符重载成员函数,用于比较用户输入密码是否正确;并用数据测试该类。 #include #include const int N=80; class CMM {

private:

char str[N]; public:

CMM(){str[0]='\\0';} CMM(const char *s) {

strcpy(str,s); }

void Show() {

if(str)cout<

void MMInput() {

cout<<\请输入密码:\ cin>>str;

}

int operator ==(const CMM &)const; };

int CMM::operator == (const CMM &s)const //重载恒等于运算符,成员函数实现 { return (strcmp(this->str,s.str)==0); } void main() {

CMM s1(\ s2.MMInput (); s1.Show(); s2.Show();

if(s1==s2)cout<<\ else cout<<\ s3.MMInput (); s1.Show(); s3.Show();

if(s1==s3)cout<<\ else cout<<\}

第9章 模板和异常处理

一、单选题

1.以下关于函数模板的叙述中正确的是( C )。 A. 函数模板也是一个具体类型的函数 B. 函数模板的类型参数与函数的参数是同一个概念 C. 通过使用不同的类型参数,函数模板可以生成不同类型的函数 D. 用函数模板定义的函数没有类型 2.已知函数模板定义如下: template T fnMin(T x, T y) { return x class A { public: A(int i){ d=i;}

ST d; }; 下列关于模板类对象的定义中,正确的是( C )。 A. Aa(5); B. Aa(5); C. Aa(5); D. Aa(5); 5. 下列叙述错误的是( C )。 A. catch(…)语句可捕获所有类型的异常 B. 一个try语句可以有多个catch语句 C. catch(…)语句可以放在catch语句的中间 D. 程序中try语句与catch语句是一个整体,缺一不可

二、填空题

1. 当在同一个程序中存在一个普通函数是一个函数模板的重载函数时,则与函数调用表达式相符合的( 普通函数 )将被优先调用执行。

2.当一个函数调用表达式只能与一个函数模板相符合时,将首先根据函数模板生成一个( 模板函数 ),然后再调用它。 3. 分析以下程序运行结果是( 函数模板

一般函数(d,d) 一般函数(d,i)

一般函数(d,i) )。

#include \template void Display(Type,Type) { cout<<\函数模板\\n\}

void Display(double,double) { cout<<\一般函数(d,d)\\n\}

void Display(double ,int ) { cout<<\一般函数(d,i)\\n\}

void main() { int i=0; double j=0.6; float k=0.5f; Display(0,i); Display(0.25,j); Display(0,k); Display(0,'h'); }

4.补充以下程序,使整个程序正确执行。