- 9
- 0
- 约8.62千字
- 约 24页
- 2020-09-01 发布于广东
- 举报
7.3 实验题
一、基础题
1.标出下列程序中的错误
class CSample
{int a=2.5; (A)实际赋值与定义的类型不符,数据成员不能在类中作初始化
CSample(); (B)
public:
CSample(int val); (C)
~CSample();}; (D)
2.在下列程序的填空中填上适当的语句,完成立方体体积的计算,并按图7-1的样式输出结果.
要求:(1)对有注释标记的语句进行功能注释。
(2)建立一个头文件和测试类文件,上机调试并输出下列结果。
程序如下:
#include iostream
using namespace std;
class cube
{
public:
cube(); //定义一个结构函数
~cube(); // 定义一个析构函数
int volume(); //定义一个成员函数
private:
int height,width,depth; //定义三个数据成员
};
cube::cube()
{ height=10;
width=8;
depth=10;
coutConstructor called.endl;
}
cube::~cube()
{
coutDestructor calledendl;
}
int cube::volume()
{
return height*width*depth;
}
void main()
{
cube cubeone; //定义一个对象
cout立方体的体积为:cubeone.volume()endl;
}
图7-1 第1题的输出示例
3. 修改下列程序中的错误,并说明调用构造函数和析构函数的次序和次数
#include iostream
using namespace std;
class CCounter
{
int value;
public:
CCountr()
{
cout CCounter Constructor1 endl;
value = 0;
}
CCountr(int val)
{
cout CCounter Constructor2 endl;
value = val;
}
~CCounter() { cout CCounter Destructor endl; }
};
class CExample
{
int value;
public:
CCounter car;
CExample()
{
cout CExample Constructor1 endl;
value = 0;
}
CExample(int val)
{
cout CExample Constructor1 endl;
value = val;
}
~CExample() { cout CExample Destructor endl; }
void Display() { cout value= value endl; }
};
void main()
{
CExample obj(350);
obj.Display();
}
先调用CExample的构造函数CExample()
然后调用CExample的构造函数CExample(int val)
然后调用CExample的析构函数~CExample()
最后调用 CCounter的析构函数~CCounter()
改为
#include iostream
using namespace std;
class CCounter
{
int value;
public:
void CCountr()
{
cout CCounter Constructor1 endl;
value = 0;
}
void CCountr(int val)
{
cout CCounter Constructor2 endl;
value = val;
}
~CCounter() { cout CCounter Destructor endl; }
};
class CExample
{
int value;
public:
CCounter car;
CExample()
{
cout CExample Constructor1 endl;
value =
原创力文档

文档评论(0)