第16题
程序阅读题
1、
#include <iostream>
using namespace std;
int& element(int x[],int index)
{
return x[index+1];
}
void main()
{
int a[]={3,7,2,1,5};
element(a,3)=9;
for(int i=0;i<5;i++)
cout<<a[i]<<’’;
}
2、
#include<iostream>
using namespace std;
class A
{
int num;
public:
A()
{
num=0;cout<<"A default constructor"<<endl;}
A(int n)
{num=n;cout<<”A constructor,num=”<<num<<endl;}
~A()
{cout<<"A destructor,num="<<num<<endl;}
};
void main()
{
A a,*p;
p=new A(2);
a=*p;
delete p;
cout<<”Exiting main”<<endl;
}
3、
#include<iostream>
using namespace std;
class Format
{
public:
virtual void header()
{cout<<"This is a head"<<endl;
}virtual void footer()
{cout<<"This is a footer"<<endl;}
virtual void body()
{cout<<"This is a body"<<endl;}
void display()
{header();body();footer();}
};
class MyFormat:public Format
{
public:
void header()
{cout<<"This is my header"<<endl;}
void footer()
{cout<<"This is my footer"<<endl;}
};
void main()
{
Format * p;
p=new Format;
p->display();
delete p;
p=new MyFormat;
p->display();
delete p;
}
4、从键盘输入8 4 3 1 9 6 1 1 2 5,给出程序的输出结果。
#include<iostream>
#include<vector>
#include<stack>
#include<iterator>
using namespace std;
main()
{
vector<int> v;
stack<int> s;
int i,n,x;
cin>>n;
for(i=0;i<n;i++)
{
cin>>x;
v.push_back(x);
}
for(vector<int>::iterator p=v.begin();p!=v.end();p++)
if(*p%2==0)
s.push(*p);
while(!s.empty())
{
cout<<s.top()<<endl;
s.pop();
}
}
5、
#include<iostream>
#include<exception>
using namespace std;
class Fract
{
int den,num;
public:
Fract(int d=0,int n=1)
{
if(n==0)
throw exception("divided by zero");
den = d;num=n;
}
int& operator[](int index)
{
if(index<0||index>1)
throw exception("index out of range");
if(index==0)
return den;
if(index==1)return num;
}
void show()
{ cout<<den<<"/"<<num<<endl;}
};
void main()
{
try
{
Fract f(0,2);
f.show();
cout<<f[1]<<"/"<<f[2]<<endl;
}
catch(exception e)
{
cout<<e.what()<<endl;
}
}