【007】動態內存管理

靜態內存:
變量(包括指針變量)、固定長度的數組、某給定的對象。
可以在代碼中通過它們的名字或者地址來訪問和使用它們。

動態內存:
由一些沒有名字、只有地址的內存塊構成,那些內存塊是在程序運行期間動態分配的。

如果沒有足夠的內存空間:
那麼new語句則拋出std::bad_alloc異常。
在用完內存塊後要用delete把它歸還給內存池。
堆是往上增長,棧是往下增長。


eg.
int *i = new int;

有一個特殊的地址叫做NULL指針,當把一個指針變量設置爲NULL時,它的含義是那個指針不再指向任何東西:
int *x;
x = NULL;   //x啥都不指向

練習:
1.效果:
2.代碼:
#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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章