C++快速入門---構造器和析構器(9)
阿新 • • 發佈:2018-11-04
C++快速入門---構造器和析構器(9)
使用面向物件的程式設計技術開發程式最基本步驟:
- 定義一個有屬性和方法的類(模板)
- 為該類建立一個變數(實現)
構造器和通常方法的主要區別:
- 構造器的名字必須和它所在的類的名字一樣
- 系統在建立某個類的例項時會第一時間自動呼叫這個類的構造器
- 構造器永遠不會返回任何值
構造器的作用是:初始化。
建立構造器,需要先把它的宣告新增到類裡:
class Car {
Car(void);
}
(注意大小寫與類名保持一致。在結束宣告之後開始定義構造器本身)
Car::Car(void)
{
color = "WHITE";
engine = "V8";
wheel = 4;
gas_tank = FULL_GAS;
}
程式碼如下:
定一個車子的顏色,引擎,油箱,輪子,跑動
#include <iostream> #include <windows.h> #define FULL_GAS 85 class Car { public: std::string color; std::string engine; unsigned int gas_tank; unsigned int wheel; Car(void);//宣告構造器 void setColor(std::string col); void setEngine(std::string eng); void setWheel(unsigned int whe); void fillTank(int liter); int running(void); void warning(void); }; //定義構造器,進行初始化 Car::Car(void) { color = "While"; engine = "V8"; wheel = 4; gas_tank = FULL_GAS;//充滿油 } void Car::setColor(std::string col) { color = col; } void Car::setEngine(std::string eng) { engine = eng; } void Car::setWheel(unsigned int whe) { wheel = whe; } void Car::fillTank(int liter) { gas_tank += liter; } int Car::running(void) { char i; std::cout << "我正在以120的時速往前移動。。。越過那高山越過那河。。。\n"; gas_tank--; std::cout << "當前還剩" << 100 * gas_tank / FULL_GAS << "%" << "油量!\n"; if (gas_tank < 10) { std::cout << "請問是否需要加滿油再行駛?(Y/N)\n"; std::cin >> i; if ('Y' == i || 'y' == i) { fillTank(FULL_GAS); } if(0 == gas_tank) { std::cout << "拋錨了。。。。"; return 1; } } return 0; } void Car::warning(void) { std::cout << "WARNING!!" << "還剩" << 100 *gas_tank / FULL_GAS << "%" << "油量!"; } int main() { Car mycar;//定一個類的物件、例項 while (!mycar.running()) { ; } return 0; }
構造物件陣列:陣列可以是任何一種資料型別,當然也包括物件。
如:Car mycar[10];
呼叫語法依舊是 :mycar[x].running
注:x代表著給定陣列元素的下標。
注意:每個類至少有一個構造器,如果你沒有在類裡定義一個構造器,編譯器就會使用如下語法替你定義一個:ClassName::ClassName(){},這是一個沒有程式碼內容的空構造器,除此之外,編譯器還會替你建立一個副本構造器(CopyConstructor)。
析構器
構造器:用來完成事先的初始化和準備工作(申請分配記憶體)
析構器:用來完成事後所必須的清理工作(清理記憶體)。當一個物件在消亡的時候,由編譯器自動呼叫。
class Car
{
Car(void); //構造器
~Car(); //析構器
}
程式碼如下:
定義存名言和作者
#include <iostream>
#include <string.h>
#include <fstream>
//存名言
class StoreQuote
{
public:
std::string quote, speaker;
std::ofstream fileOutput;
StoreQuote();
~StoreQuote();
void inputQuote();
void inputSpeaker();
bool write();
};
//構造器
StoreQuote::StoreQuote()
{
//開啟一個檔案
fileOutput.open("test.txt",std::ios::app);//app追加方式開啟
}
//析構器
StoreQuote::~StoreQuote()
{
//關閉檔案
fileOutput.close();
}
void StoreQuote::inputQuote()
{
//寫入名言
std::getline(std::cin, quote);
}
void StoreQuote::inputSpeaker()
{
//寫入名言的作者
std::getline(std::cin, speaker);
}
bool StoreQuote::write()
{
if(fileOutput.is_open())
{
//把剛才兩個quote和speaker寫入檔案裡面
fileOutput << quote << "|" << speaker << "\n";
return true;
}
else
{
return false;
}
}
int main()
{
StoreQuote quote;
std::cout << "請輸入一句名言:\n";
quote.inputQuote();
std::cout << "請輸入作者:\n";
quote.inputSpeaker();
if (quote.write())
{
std::cout << "成功寫入檔案^_^";
}
else
{
std::cout << "寫入檔案失敗T_T";
return 1;
}
return 0;
}