// This program demonstrates when a constructor executes. #include <iostream> using namespace std; class Demo { public: Demo() { cout << "Now the constructor is running.n"; } }; int main() { cout << "This is displayed before the object is created. n"; Demo demoObj; // Define a Demo object cout << "This is displayed after the object is created.n"; return 0; }程式輸出結果為:
This is displayed before the object is created.
Now the constructor is running.
This is displayed after the object is created.
Demo:: Demo () // 建構函式 { cout << "Now the constructor is running. n"; }
#include <iostream> #include <iomanip> using namespace std; // Sale class declaration class Sale { private: double taxRate; public: Sale(double rate) // Constructor with 1 parameter { taxRate = rate; // handles taxable sales } Sale () // Default constructor { taxRate = 0.0 // handles tax-exempt sales } double calcSaleTotal(double cost) { double total = cost + cost*taxRate; return total; } }; int main() { Sale cashier1(.06); // Define a Sale object with 6% sales tax Sale cashier2; // Define a tax-exempt Sale object // Format the output cout << fixed << showpoint << setprecision (2); // Get and display the total sale price for two $24.95 sales cout << "With a 0.06 sales tax rate, the totaln"; cout << "of the $24.95 sale is $"; cout << cashier1.calcSaleTotal(24.95) << endl; cout << "nOn a tax-exempt purchase, the totaln"; cout << "of the $24.95 sale is, of course, $"; cout << cashier2.calcSaleTotal(24.95) << endl; return 0; }程式輸出結果:
With a 0.06 sales tax rate, the total
of the $24.95 sale is $26.45
On a tax-exempt purchase, the total
of the $24.95 sale is, of course, $24.95
Sale cashier1(.06);
Sale cashier2;
Sale cashier2 () ; // 錯誤
Sale cashier2; // 正確
class Sale //非法宣告 { private: double taxRate; public: Sale() //無實參的預設建構函式 { taxRate = 0.05; } Sale (double r = 0.05) //有預設實參的預設建構函式 { taxRate = r; } double calcSaleTotal(double cost) { double total = cost + cost * taxRate; return total; }; };可以看到,第一個建構函式沒有形參,第二個建構函式有一個形參,但它有一個預設實參。如果一個物件被定義為沒有參數列,那麼編譯器將無法判斷要執行哪個建構函式。
//This program demonstrates a destructor. #include <iostream> using namespace std; class Demo { public: Demo(); // Constructor prototype ~Demo(); // Destructor prototype }; Demo::Demo() // Constructor function definition { cout << "An object has just been defined,so the constructor" << " is running.n"; } Demo::~Demo() // Destructor function definition { cout << "Now the destructor is running.n"; } int main() { Demo demoObj; // Declare a Demo object; cout << "The object now exists, but is about to be destroyed.n"; return 0; }程式輸出結果:
An object has just been defined, so the constructor is running.
The object now exists, but is about to be destroyed.
Now the destructor is running.