c++课后习题解答6-10 下载本文

6.使用new创建一个对象数组,该数组用指针pa指向,并使数组的3个元素都是类A的对象a1的值。应该是 A a1,*pa; pa=new A[3]; pa[0]=pa[1]=pa[2]=a1; 。

7.在某个函数体内定义一个静态类的对象sa,应该是 static A sa; 。

8.定义一个类A的对象a1,并给它赋值,其实参值为8,应该是 A a1(8); 。

7.4 分析下列程序的输出结果 1.

#include class A { public: A(int i) { a=i; } A() { a=0;

cout<<\ } ~A()

{ cout<<\ } void Print()

{ cout<

A a[4],*p; int n=1; p=a;

for(int i=0;i<4;i++) a[i]=A(++n); for(i=0;i<4;i++) (p+i)->Print(); }

答: 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

11

3 4 5

Destructor called. 5 Destructor called. 4 Destructor called. 3 Destructor called. 2

2.

#include class B {

public:

B(int i) { b=i; } B() {

b=0;

cout<<\ } ~B()

{ cout<<\ } void Print()

{ cout<

B *pb[4]; int n=1;

for(int i=0;i<4;i++) pb[i]=new B(n++); for(i=0;i<4;i++) pb[i]->Print(); for(i=0;i<4;i++) delete *(pb+i); } 答: 1 2 3 4

Destructor called. 1 Destructor called. 2 Destructor called. 3 Destructor called. 4

12

3.

#include class C { public: C(int i) { c=i; } C() { c=0;

cout<<\ }

~C()

{ cout<<\ } void Print()

{ cout<

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