C++实验三构造函数与析构函数

实验     构造函数与析构函数
1、实验目的:
1)掌握构造函数和析构函数定义方法;
2)掌握构造函数的重载、具有默认值的构造函数的使用方法;
3)加深对构造函数的特殊用途的理解。
2、实验内容:
2.1 分析程序指出程序运行的结果
1)p106 3.15
程序代码
运行结果
2)分析下面程序中的对象传递,写出输出结果
#include<iostream.h>
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;
   cylinder2.setcylinder(12.3,18.7);
   cout<<"the radius of cylinder1 is:\t"<&adius()<<endl;
   cout<<"the height of cylinder1 is:\t"<&height()<<endl;
   cout<<"the volume of cylinder1 is:\t"<<cylinder1.volume()<<endl;
   cout<<"the surfacearea of cylinder1 is:\t"<<cylinder1.surface_area()<<endl;
   cout<<"the radius of cylinder2 is:\t"<&adius()<<endl;
   cout<<"the height of cylinder2 is:\t"<&height()<<endl;
   cout<<"the volume of cylinder2 is:\t"<<cylinder2.volume()<<endl;
   cout<<"the surfacearea of cylinder2 is:\t"<<cylinder2.surface_area()<<endl;
}
运行结果
3 分析下面的程序,指出程序的错误。
#include<iostream.h>
#include<stdlib.h>
class Sample
{
   int i;
public:
int j;
   Sample(int x)
   {
      i=x;//cout<<"i="<<i<<endl;
   }
雪鹀
   ~Sample()
   { 
      exit(1);
      cout<<"撤消"<<endl;
   }
};
void main()
Sample a1(10),a2(20);
exit(1)
   cout<<"撤消"<<endl;
}
4)将下面的程序补充完整
#include<iostream.h>
我不是宋承宪歌词class test
{
private:
   int num;
   double f1;蔡琳近况
public:
   test();
   test(              );
   getint(){return num;}
   double getfloat(){return f1;}
};
test::test()
{
   cout<<"默认初始化"<<endl;
   cout<<"调用构造函数1"<<endl;
              num  =0;
              f1 =0.0;
}
test:: test(            )
{
   cout<<"初始化pubmedline"<<endl;
   cout<<"调用构造函数2"<<endl;
拉伸模量     
}
void main()
{
   test a;
  test b(2,5.5);
}
2.2 编写并调试程序
编写一个实现两个数相减的类的测试程序,请写出类的定义,构成一个完整的程序,要求调用类的构造函数和析构函数时均有明确的输出信息。
#include<iostream.h>
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);
   t.print();理性与感性作品音乐会
}
程序运行结果:
3.实验总结

本文发布于:2024-09-23 04:23:43,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/434993.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:程序   结果   实验   写出   指出
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议