1、实验目的:
1)掌握构造函数和析构函数定义方法;
2)掌握构造函数的重载、具有默认值的构造函数的使用方法;
3)加深对构造函数的特殊用途的理解。
2、实验内容:
1)p106 3.15
程序代码:
运行结果:
#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.实验总结: