C++快速入门---动态内存管理(23)

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;
}

猜你喜欢

转载自blog.csdn.net/xiaodingqq/article/details/83819036