下载此文档

《面向对象程序设计》实验指导书(实验二).doc


文档分类:IT计算机 | 页数:约13页 举报非法文档有奖
1/13
下载提示
  • 1.该资料是网友上传的,本站提供全文预览,预览什么样,下载就什么样。
  • 2.下载该文档所得收入归上传者、原创者。
  • 3.下载的文档,不会出现我们的网址水印。
1/13 下载此文档
文档列表 文档介绍
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转载请标明出处.

相关文档 更多>>
非法内容举报中心
文档信息
  • 页数13
  • 收藏数0 收藏
  • 顶次数0
  • 上传人beny00001
  • 文件大小41 KB
  • 时间2022-01-21