admin 管理员组文章数量: 1087135
2023年12月24日发(作者:struts2返回json)
实验三 构造函数与析构函数
1、实验目的:
1)掌握构造函数和析构函数定义方法;
2)掌握构造函数的重载、具有默认值的构造函数的使用方法;
3)加深对构造函数的特殊用途的理解。
2、实验内容:
2.1 分析程序指出程序运行的结果:
1)p106 3.15
程序代码:
运行结果:
2)分析下面程序中的对象传递,写出输出结果。
#include
Using std::cout;
Using std::endl;
class Cylinder
{
public:
Cylinder(){}
Cylinder(double r,double h);
void setcylinder(double r,double h);
double getradius(){return radius;}
double getheight(){return height;}
double volume();
double surface_area();
private:
double radius;
double height;
};
const double PI=3.1415926;
Cylinder::Cylinder(double r,double h)
{
radius=r;
height=h;
}
void Cylinder::setcylinder(double r,double h)
{
radius=r;
height=h;
}
double Cylinder::volume()
{
double vol;
vol=PI*radius*radius*height;
return vol;
}
double Cylinder::surface_area()
{
double area;
area=2*PI*radius*height+2*PI*radius*radius;
return area;
}
void main()
{
Cylinder cylinder1(7.0,12.0),cylinder2;
inder(12.3,18.7);
cout<<"the radius of cylinder1 is:t"< cout<<"the height of cylinder1 is:t"< cout<<"the volume of cylinder1 is:t"<<()< cout<<"the surfacearea of cylinder1 is:t"< cout<<"the radius of cylinder2 is:t"< cout<<"the height of cylinder2 is:t"< cout<<"the volume of cylinder2 is:t"<<()< cout<<"the surfacearea of cylinder2 is:t"< } 运行结果: 3) 分析下面的程序,指出程序的错误。 #include #include class Sample { int i; public: int j; Sample(int x) { i=x;//cout<<"i="< } ~Sample() { exit(1); cout<<"撤消"< } }; void main() { Sample a1(10),a2(20); exit(1); cout<<"撤消"< } 4)将下面的程序补充完整 #include class test { private: int num; double f1; public: test(); test( ); getint(){return num;} double getfloat(){return f1;} }; test::test() { cout<<"默认初始化"< cout<<"调用构造函数1"< num =0; f1 =0.0; } test:: test( ) { cout<<"初始化"< cout<<"调用构造函数2"< } void main() { test a; test b(2,5.5); } 2.2 编写并调试程序 编写一个实现两个数相减的类的测试程序,请写出类的定义,构成一个完整的程序, 要求调用类的构造函数和析构函数时均有明确的输出信息。 #include Using std::cout; Using std::endl; class Cha { int a,b; public: Cha(int,int); void print(); }; Cha::Cha(int x,int y) { } void Cha::print() { } void main() { Cha t(88,32); (); } 程序运行结果: 3.实验总结:
版权声明:本文标题:C++实验三构造函数与析构函数 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1703383558a448941.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论