当前位置:文档之家› C++习题(静态成员)

C++习题(静态成员)


n=2, sum=2 n=3, sum=5 n=5, sum=10
4. 分析以下程序执行的结果
#include<iostream.h> class Sample { int A; static int B; public: Sample(int a){A=a, B+=a;} static void func(Sample s); }; void Sample::func(Sample s) { cout<<"A="<<s. A<<",B="<<B<<endl; } int Sample::B=0; void main() { Sample s1(2),s2(5); Sample::func(s1); Sample::func(s2); }
x=10, y=20
x=0, y=0 x=1, y=2 x=10, nclude<iostream.h> class Sample { public: int x; int y; void disp() { cout<<"x="<<x<<",y="<<y<<endl; } }; void main() { int Sample::*pc; Sample s,*p=&s; pc=&Sample::x; p->*pc=10; pc=&Sample::y; p->*pc=20; p->disp(); }
3. 分析以下程序执行的结果
#include<iostream.h> class Sample { int n; static int sum; public: Sample(int x) {n=x;} void add() {sum+=n;} void disp() { cout<<"n="<<n<<",sum="<<sum<<endl; } }; int Sample::sum=0; // 静态数据成员赋初值 void main() { Sample a(2),b(3),c(5); a.add(); a.disp(); b.add(); b.disp(); c.add(); c.disp(); }
constructing object: x=1
2. 分析以下程序执行的结果
#include<iostream.h> class Sample { public: Sample(); Sample(int); ~Sample(); void display(); protected: int x; }; Sample::Sample() { x=0; cout<<"constructing normally\n"; } Sample::Sample(int m) { x=m; cout<<"constructing with a number:"<<x<<endl; }
A=2, B=7 A=5, B=7
5. 分析以下程序执行的结果
#include<iostream.h> class Sample { int x,y; public: Sample(){x=y=0;} Sample(int a,int b){x=a;y=b;} void disp() { cout<<"x="<<x<<",y="<<y<<endl; } }; void main() { Sample s1,s2(1,2),s3(10,20); Sample *pa[3]={&s1,&s2,&s3}; for(int i=0;i<3;i++) pa[i]->disp(); }
v=2, t=7
9. 分析以下程序执行的结果
#include<iostream.h> class Sample { public: int x; int y; void disp() { cout<<"x="<<x<<",y="<<y<<endl; } }; void main() { int Sample::*pc; Sample s; pc=&Sample::x; s.*pc=10; pc=&Sample::y; s.*pc=20; s.disp(); }
C++习题(静态成员) 习题(静态成员) 习题
1. 分析以下程序执行的结果
#include<iostream.h> class Sample { int x; public: Sample(int a) { x=a; cout<<"constructing object:x="<<x<<endl; } }; void func(int n) { static Sample obj(n); } void main() { func(1); func(10); }
v=2, t=7
8. 分析以下程序执行的结果
#include<iostream.h> class Sample { int x; int y; public: Sample(int a,int b) { x=a;y=b; } int getx() {return x;} int gety() {return y;} }; void main() { int (Sample::*fp)(); fp=&Sample::getx; Sample s(2,7),*p=&s; int v=(p->*fp)(); fp=&Sample::gety; int t=(p->*fp)(); cout<<"v="<<v<<",t="<<t<<endl; }
void Sample::display() { cout<<"display a number:"<<x<<endl; } Sample::~Sample() { cout<<"destructing\n"; } void main() { Sample obj1; Sample obj2(20); obj1.display(); obj2.display(); } constructing normally constructing with a number:20 display a number: 0 display a number: 20 destructing destructing
x=10, y=20
7. 分析以下程序执行的结果
#include<iostream.h> class Sample { int x; int y; public: Sample(int a,int b) { x=a;y=b; } int getx(){return x;} int gety(){return y;} }; void main() { int (Sample::*fp)(); fp=&Sample::getx; Sample s(2,7); int v=(s.*fp)(); fp=&Sample::gety; int t=(s.*fp)(); cout<<"v="<<v<<",t="<<t<<endl; }
相关主题