当前位置:首页 > C++程序设计模拟试题及答案
};
class Der1:public Base {public:
void display(){cout<<\};
class Der2:public Base {public:
void display(){cout<<\};
void fun(______________) {p->display();} void main() {Der1 b1; Der2 b2;
Base * p=&b1; fun(p); p=&b2; fun(p); }
答案:virtual void display()=0;,Base *p
[解析]抽象类有纯虚函数,派生类为display。结果fun函数用指针做参数。
5. 下面程序中用来求数组和。请在下面程序的横线处填上适当内容,以使程序完整,并使程序 的输出为:s=150。 #include
Arr():a(0),n(0){} Arr(int *aa, int nn) {n=nn;
a=new int[n];
for(int i=0;i ~Arr(){delete a;} _____________; {return *(a+i);} }; void main() {int b[5]={10,20,30,40,50}; Arr a1(b,5); int i=0,s=0; _____________ s+=a1.GetValue(i); cout<<\} 25 答案:int GetValue(int i),for(;i<5;i++) [解析]函数调用GetValue,由此可知要定义该函数,循环求和,循环5次。 五、程序分析题(本大题共4小题,每小题5分,共20分) 1. 给出下面程序输出结果。 #include 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 cout<<**p2< 答案:20 [解析]p1指向b,而p指向p1的地址。*p2表示p1的地址,p1的地址就是&b,即*p2是&b,所以 **p2就是b变量的值。 3. 给出下面程序输出结果。 #include Base(int y=0) {Y=y;cout<<\\n\~Base() {cout<<\\n\void print() {cout < class Derived:public Base {private: int Z; 26 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 {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函数。 27 六、程序设计题(本大题共1小题,共10分) 1. 编写类String的构造函数、析构函数和赋值函数和测试程序。 已知类String的原型为: #include 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() 28
共分享92篇相关文档