C++快速入門---動態記憶體管理(23)
阿新 • • 發佈:2018-11-18
C++快速入門---動態記憶體管理(23)
靜態記憶體:變數(包括指標變數)、固定長度的陣列、某給定類的物件
動態記憶體:由一些沒有名字、只有地址的記憶體塊構成的,那些記憶體塊是在程式執行期間動態分配的。
用new向記憶體池申請記憶體
用delete來釋放記憶體
注意:在用完記憶體塊之後,應該用delete語句把它還給記憶體池。另外作為一種附加的保險措施,在釋放了記憶體塊之後還應該把與之關聯的指標設定為NULL。
#include <iostream> #include <string> class Company { public: Company(std::string theName); virtual void printInfo(); protected: std::string name; }; class TechCompany : public Company { public: TechCompany(std::string theName, std::string product); virtual void printInfo(); private: std::string product; }; Company::Company(std::string theName) { name = theName; } void Company::printInfo() { std::cout << "這個公司的名字叫:" << name << ".\n"; } TechCompany::TechCompany(std::string theName, std::string product) : Company(theName) { this->product = product; } void TechCompany::printInfo() { std::cout << name << "公司大量生產了 " << product << "這款產品!\n"; } int main() { Company *company = new Company("APPLE"); company->printInfo(); delete company; company = NULL; company = new TechCompany("APPLE", "IPHONE"); company->printInfo(); delete company; company = NULL; return 0; }