您的位置:首页 > 编程语言 > C语言/C++

[C++]实验五:掌握类的声明和对象的定义

2006-01-22 21:19 627 查看
/*
1.构造计时类
要求:建立Watch类,用来仿效秒表跟踪消逝的时间。
提供两个成员函数Start()与Stop(),分别打开与关闭计时器。
在该类中还包含一个Show()的成员函数,显示消逝的时间(以秒为单位)。
*/

#include <time.h>
#include <iostream>
using namespace std;

class watch {

public:
void show();
void start();
void stop();

private:
double time;
};

inline void watch::show()
{
cout << time << endl;
}

inline void watch::start()
{
clock();
}

inline void watch::stop()
{
clock_t t;
t = clock();
time = (double)t / CLOCKS_PER_SEC; /* 转换成秒 */
}

void main()
{
watch p1;
int i=0,j=0;
p1.start();
for (; i<100000000 ; i++)
for (; j<10000000 ; j++)
(i>j)?i:j;
p1.stop();
p1.show();
}

// 清翔兔
// 2005/11/01

/*
2.设计一个立方体类Box,它能计算并输出立方体的体积与表面积。
*/
#include <iostream>
using namespace std;

class Box {
public:
void init (double,double,double);
inline double area (){return 2*(l*w+h*l+w*h);};
double vol(){return w*l*h;};
private:
double l,w,h;
};

inline void Box::init( double a =0, double b = 0, double c = 0 )
{
l = a; w = b; h = c;
}

void main ()
{
Box l1;
l1.init (1,2,3);
cout << l1.area() << "/n"
<< l1.vol() << endl;
}

// 清翔兔
// 2005/11/01

/*
3.设计一个采用类结构的方式求n!的程序。
*/

#include <iostream>
using namespace std;

class factorial {
public:
factorial(unsigned int num): _n(num){};
unsigned long int facrun (unsigned int);
unsigned long int fac() {return facrun (_n);};
private:
unsigned int _n;
};

unsigned long int factorial::facrun (unsigned int n)
{
unsigned long int result;
if(n==1)
result=1;
else
result=facrun(n-1)*n;
return result;
}

void main()
{
factorial f1(4);
cout << f1.fac() << endl;
}

// 清翔兔
// 2005/11/01
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: