void main() {
C *p;
p=new C[4]; int n=1;
for(int i=0;i<4;i++) p[i]=C(n++); for(i=0;i<4;i++) p[i].Print(); delete []p; }
答: Default constructor called. 0 Default constructor called. 0 Default constructor called. 0 Default constructor called. 0 Destructor called. 2 Destructor called. 3 Destructor called. 4 Destructor called. 5 2 3 4 5
Destructor called. 5 Destructor called. 4 Destructor called. 3 Destructor called. 2
13
4.
#include class D { public: D() {
d1=d2=0;
cout<<\ }
D(int i,int j) {
d1=i; d2=j;
cout<<\ } ~D()
{ cout<<\ } void Set(int i,int j) { d1=i;d2=j; } private: int d1,d2;
};
void main() {
int n(10),m(20);
D d[4]={D(5,7),D(3,6),D(7,9),D(1,4)}; for(int i=0;i<4;i++) d[i].Set(n++,m++); }
答: Constructor called. d1=5,d2=7 Constructor called. d1=3,d2=6 Constructor called. d1=7,d2=9 Constructor called. d1=1,d2=4 Destructor called. d1=13,d2=23 Destructor called. d1=12,d2=22 Destructor called. d1=11,d2=21 Destructor called. d1=10,d2=20
5.
#include class E {
public:
E(int i,int j) {
e1=i; e2=j;
cout<<\ }
void FunE(E *e)
14
{
e1=e->e1; e2=e->e2;
cout<<\ }
void FunE(E &e) {
e1=e.e1; e2=e.e2;
cout<<\ } private: int e1,e2; }; void main() {
E a(5,6),b(3,4); a.FunE(&b); b.FunE(a); }
答: Constructor called. e1=5,d2=6 Constructor called. e1=3,e2=4 In FunE(E &e). e1=3,e2=4 In FunE(E &e). e1=3,e2=4
6.
#include class F {
public:
class G {
public: G() {} G(int i) { g=i; } int GetValue() { return g; } void Print(F *p); private: int g; }myg;
friend class G; F(int i,int j):myg(i) { f=j; } private: int f; };
void F::G::Print(F *p) {
15