内容发布更新时间 : 2025/1/11 0:33:51星期一 下面是文章的全部内容请认真阅读。
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
cout<<\ } ~A()
{ cout<<\ } void Print()
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
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
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
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
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
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