第1题
读程序写结果
1.
#include <iostream.h>
class CSample
{
private:
int n;
static int k;
public:
CSample(int i){n=i;k++;}
void disp();
};
void CSample::disp()
{cout<<"n="<<n<<",k="<<k<<endl;}
int CSample::k=0;
int main()
{CSample a(10),b(20),c(30);
a.disp();
b.disp();
c.disp();
}2.
#include <iostream.h>
class Sample
{int n;
public:
Sample(){}
Sample(int m){n=m;
}
Sample operator--(int)
{Sample old=*this;
n--;
return old;
}
void disp(){cout<<"n="<<n<<endl;}
};
int main()
{Sample s(10);
s--;
s.disp();
}3.
#include <iostream.h>
#include <string.h>
template <class T>
T max(T x, T y)
{
return (x > y ? x : y);
}
char *max(char *x, char *y)
{
if (strcmp(x, y) >= 0)
return x;
else
return y;
}
int main()
{
cout << max(2, 5) << endl;
cout << max(3.14,4.12) << endl;
cout << max("China", "Beijing") << endl;
}4.
#include <stack>
#include <iostream>
#include <string>
using namespace std;
int main() {
stack<char> s;
string str;
cin >> str;//从键盘输入字符串LoveChina
for(string::iterator iter = str.begin(); iter != str.end(); ++iter)
s.push(*iter);
while (!s.empty()) {
cout << s.top();
s.pop();
}
cout << endl;
}5.
#include <iostream>
using namespace std;
int divide(int x, int y)
{
if (y == 0)
throw x;
return x / y;
}
int main()
{try {
cout << "8/3 = " << divide(8, 3) << endl;
cout << "6/0 = " << divide(6, 0) << endl;
cout << "9/2 = " << divide(9, 2) << endl;
} catch (int e) {
cout << e << " is divided by zero!" << endl;
}
cout << "That is ok." << endl;
}