1. 程式人生 > >面向對象程序設計2

面向對象程序設計2

時間 構建 同時 AS ostream time 無法 req main

從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;
}//電梯停靠

面向對象程序設計2