word
word
1 / 13
word
实验二 类与对象㈡——对象初始化、对象数据与指针
一、实验目的
1.理解构造函数、析构函数的意义与作用,掌握构造函数、析构函数的定义与调用时间,熟悉构造函数的种类;
2.理解thiing!"<<endl;}
~ Myclass (void)
{ cout<<"destructing!"<<endl;}
};
void main()
{ Myclass ob;}
问题:
⑴ 运行程序的输出结果为:
Constructing!
Destructing!
Press any key to continue
⑵ 该输出结果说明构造函数Myclass ( )是在 创建对象时 执行的,而析构函数~ Myclass ( )是在是在 对象生存期完毕时 执行的。
⑶ 将main( )中的“Myclass ob;〞改为:“Myclass ob[2];〞后,运行程序的输出结果为:
Constructing!
Constructing!
Destructing!
Destructing!
Press any key to continue
⑷ 将main( )中的 “Myclass ob[2];〞改为:“Myclass *ob;ob=new Myclass[2];〞后,运行程序的输出结果为:
Constructing!
Constructing!
Press any key to continue
⑸ 在⑷的根底上,在程序的末尾参加:“delete []ob;〞后,运行程序的输出结果为:
Constructing!
Constructing!
Destructing!
word
word
4 / 13
word
Destructing!
Press any key to continue
⑹ 比拟⑶—⑸的输出结果,说明:
。
程序2〔〕
#include<>
class A
{ private:
int a,b;
public:
A(void)
{ a=0;b=0;}
A(int x1,int x2)
{a=x1;b=x2;}
A(A &ob)
{ a=;b=;
cout<<"拷贝构造函数被调用!"<<endl;
}
void print(void)
{ cout<<"a="<<a<<" b="<<b<<endl;}
};
void main()
{ A ob1(20,30),ob;
A ob2(ob1);
();
// ob=ob1;
// ();
}
问题:
⑺ 运行该程序的输出结果为:
拷贝构造函数被调用!
a=20 b=30
Press any key to continue
⑻ 程序中的成员函数A(A &ob)称为 拷贝构造函数 ,该函数的执行时间是在执行用类的一个对象初始化类的另一个对象被调用的。
⑼ 将main()中的“A ob2(ob1);〞改为“A ob2=ob1;〞,重新运行程序,观察输出结果,说明拷贝构造函数也可在 用类的一个对象给另一个类的对象赋值时 时调用。
⑽ 将main()函数中加注释的语句去掉前面的“//〞,重新运行程序,观测输出结果,说明执行“ob=ob1;〞时 不 调用拷贝构造函数,原因是“ob=ob1;〞只是对象的 赋值 。
word
word
5 / 13
word
㈡ 知识应用实验
1.分析如下程序,写出程序的输出结果,再上机运行程序验证其正确性,如果不正确,请认真分析出错原因。
你分析的程序输出结果是:
构造函数被调用!
Main:a=10 b=10
调用func1:
拷贝构造函数被调用!
Func1: a=10 b=10
析构函数被调用!
调用func2:
Func2: a=10 b=10
调用func3:
Main:a=10 b=10
析构函数被调用!
程序3〔〕
#include<>
class Myclass
{ private:
int a,b;
public:
Myclass(int x1=0,int x2=0)
{a=x1;b=x2;
cout<<"构造函数被调用!"<<
《面向对象程序设计》实验指导书(实验二) 来自淘豆网www.taodocs.com转载请标明出处.