最新c++题库及答案 下载本文

内容发布更新时间 : 2024/4/29 0:36:33星期一 下面是文章的全部内容请认真阅读。

1. 给出下面程序输出结果。 #include class example {int a; public:

example(int b=5){a=b++;}

void print(){a=a+1;cout <

void main() {example x;

const example y(2); x.print(); y.print(); }

答案:62

[解析]x是普通对象,调用普通的print函数;而y常对象,调用常成员函数。 2. 给出下面程序输出结果。 #include void main() { int *p1;

int **p2=&p1; int b=20; p1=&b;

cout<<**p2<

答案:20

[解析]p1指向b,而p指向p1的地址。*p2表示p1的地址,p1的地址就是&b,即*p2是&b,所以

**p2就是b变量的值。 3. 给出下面程序输出结果。 #include class Base {private: int Y; public:

Base(int y=0) {Y=y;cout<<\\n\~Base() {cout<<\\n\void print() {cout <

class Derived:public Base {private: int Z;

public:

Derived (int y, int z):Base(y) {Z=z;

cout<<\\n\}

~Derived() {cout<<\~Derived()\n\void print() {Base::print(); cout<

void main()

{Derived d(10,20); d.print(); }

答案:Base(10) Derived(10,20) 10 20

~Derived() ~Base()

[解析]派生类对象,先调用基类构造函数输出Base(10),后调用派生类构造函数输出 Derived(10,20),后执行d.print(),调用派生类的print,再调用Base::print()输出10,后返回 输出z的值20。后派生类析构,再基类析构。 4. 给出下面程序输出结果。 #include class A {public: A()

{cout<<\构造函数\n\virtual void fun()

{cout<<\函数\n\};

class B:public A {public: B()

{cout<<\构造函数\n\

void fun() {cout<<\函数\n\};

void main() {B d;}

答案:A构造函数 A::fun()函数 B构造函数

B::fun()calle函数

[解析]定义派生类对象,首先调用基类构造函数,调用A类中fun(),然后调用B类的构造函数

,在调用B的fun函数。

六、程序设计题(本大题共1小题,共10分)

1. 编写类String的构造函数、析构函数和赋值函数和测试程序。 已知类String的原型为: #include #include class String {public:

String(const char *str=NULL); // 普通构造函数 String(const String &other); // 拷贝构造函数 ~String(); // 析构函数

String & operator=(const String &other); // 赋值函数 void show()

{cout<

private:

char *m_data; // 用于保存字符串 };

答案:String::~String()

{delete[]m_data;//由于m_data是内部数据类型,也可以写成delete m_data; }

String::String(const char *str) {if(str==NULL)

{m_data=new char[1];//若能加NULL判断则更好 *m_data=\0; } else

{int length=strlen(str);

m_data=new char[length+1]; //若能加NULL判断则更好 strcpy(m_data, str); } }

String::String(const String &other) {int length=strlen(other.m_data);

m_data=new char[length+1];//若能加NULL判断则更好 strcpy(m_data, other.m_data); }

String & String::operator=(const String &other) {if(this==&other) return *this;

delete[]m_data;

int length=strlen(other.m_data);

m_data=new char[length+1];//若能加NULL判断则更好 strcpy(m_data, other.m_data); return *this; }

void main()

{String str1(\str1.show(); str2=str1; str2.show(); String str3(str2); str3.show(); }__

C++程序设计模拟试卷(三)

一、单项选择题(本大题共20小题,每小题1分,共20分)在每小题列出的四个备选项中 只有一个是符合题目要求的,请将其代码填写在题后的括号内。错选、多选或未选均无 分。

1. 设有定义int i;double j=5;,则10+i+j值的数据类型是() A. int B. double C. float D. 不确定 答案:B

解析:考察数据的转换,j是double类型,运算只能作同类型的运算,所以要转换,而int能自动

转换为double类型,所以结果是double类型。

2. 要禁止修改指针p本身,又要禁止修改p所指向的数据,这样的指针应定义为() A. const char *p=“ABCD”; B. char *const p=“ABCD”; C. char const *p=“ABCD”; D. const char * const p=“ABCD”; 答案:D

解析:const char *p说明禁止通过p修改所指向的数据。char * const p则说明不能修改 指针p的地址。因此const char * const p=“ABCD”;它禁止修改指针p本身,又禁止修改p