說明
我們在以前使用c語言實現的時候:
定義變量--------->通過函數填充變量---------->去顯示變量
使用C++:
定義的變量(類內的私有數據成員)
通過函數填充變量(初始化)
去顯示變量(行爲)
代碼
#include <iostream>
#include <time.h>
#include <windows.h>
#include <iomanip>
using namespace std;
class Cloak
{
public:
Cloak()
{
time_t t = time(NULL);
struct tm * pt = localtime(&t);
_hour = pt->tm_hour;
_min = pt->tm_min;
_sec = pt->tm_sec;
}
void run()
{
while(1)
{
tick();
display();
}
}
void tick()
{
Sleep(1000);
if(++_sec == 60)
{
_sec = 0;
if(++_min == 60)
{
if(++_hour == 24)
{
_hour = 0;
}
}
}
}
void display()
{
system("cls");
cout<<setfill('0')<< setw(2)<<_hour<<":"<<
setw(2)<<_min<<":"<<
setw(2)<<_sec<<endl;
}
private:
int _hour;
int _min;
int _sec;
};
class Car
{
public:
Car(string c = "red",string b = "porsche",float o = 0)
{
colar = c;
brand = b;
gas = o;
}
void addGas(float gasMount)
{
gas += gasMount;
}
void run()
{
while(1)
if(gas>0)
{
Sleep(1000);
cout<<"running"<<endl;
cout<<"color = "<<colar<<endl;
cout<<"brand = "<<brand<<endl;
gas -=10;
cout<<"gas = "<<gas<<endl;
cout<<"--------------------"<<endl;
}
else
{
cout<<"need add gas"<<endl;
break;
}
}
private:
string colar;
string brand;
float gas;
};
int main()
{
Cloak c;
c.run();
Car ca;
ca.addGas(200);
ca.run();
return 0;
}
測試結果爲:
打印當前時間:
跑車在燒油:
小結
面向對象:
單獨存放數據,單獨初始化,寫行爲,通過類對象體現行爲。
面向對象程序:通過對象組織行爲,通過對象調用方法。
通過對象去解決問題,通過類生成對象
例如我們自實現的mystring
通過mystring生成對象
把所有的行爲放在類裏面,生成對象,然後通過對象的行爲或者方法解決問題