Fork me on GitHub

面向对象程序设计2

从C语言看电梯

在使用C语言编写电梯作业时,大致的结构是先建立一个结构体,用来储存所有的请求,内部含有请求层数,请求时间,目的层数,当前层数等变量,然后在main函数中进行一些预处理,再构建上行下行等一些外部函数,并在函数中进行一系列请求的处理。


从C++类看电梯

在面向对象程序设计的第一次作业中,初次接触类的概念,有种迷迷糊糊把作业写完的感觉,但是在写完之后的调试中,随着自己修改的错误的增多,对于类的使用也有了一些概念。代码整体包含了一个电梯类以及一个main函数,电梯类中包含了请求时间,请求层数等一系列请求,同时C语言中的外部函数同样放到了电梯的类中,在main函数中进行一些简单的处理。


对比

相对于C++来说,C语言整体结构较为臃肿,一旦出现错误的话,检查错误比较繁琐,而C++的类则结构比较简单明了,将整个代码模块化,结构清晰。

虽然已经使用C++的类写过一次电梯,但其实对于面向对象和面向过程的概念还不是特别清楚,也无法明显区分,希望接下来的作业中可以逐渐明晰。


下面是C++中的电梯类的代码

class Elevator
{
public:
	int time;//总时间
	int requesttime;//请求时间
	int waitfloor;//请求层数
	int requestfloor;//目的层数
	int currentfloor;//当前层数
	Elevator();
	~Elevator();


	int gotofloor(int requesttime,int requestfloor,int time,int waitfloor,int currentfloor);//前往目的层数
	int stop(int time,int currentfloor);//停止
	
};
#include "stdafx.h"
#include "Elevator.h"
#include<iostream>
#include<stdio.h>
using namespace std;
Elevator::Elevator()
{
}


Elevator::~Elevator()
{
}


int Elevator::gotofloor(int requesttime,int requestfloor,int time,int waitfloor,int currentfloor)
{
	int g, h;
	if (time < requesttime)time = requesttime;
	g = waitfloor - currentfloor;
	if (g < 0)g = -g;
	h = waitfloor - requestfloor;
	if (h < 0)h = -h;
	time = time + g + h;
	return time;
}//电梯送乘客前往目的地

int Elevator::stop(int time,int currentfloor)
{
	time++;
	return time;
}//电梯停靠
posted @ 2018-05-06 18:06  Destr  阅读(255)  评论(1编辑  收藏  举报