#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;
}
第一处:使用string字符串的地方,不能少了std命名空间
第二处:子类构造方法继承基类构造方法时,实现的格式。后面加【:】
第三处:删除指针后,要清理指针,把指针赋值NULL
动态数组:
int a[100];
int *x = a;
a[1] 等价于 *(x+1)、
a[2] 等价于 *(x+2)
新建一个动态数组:
手动确定大小
int *x = new int [10];
由变量确定大小
int count = 10;
int *x = new int[count];
删除一个动态数组:
delete [] x;
关于删除申请的堆内存:
Company *company = new Company("APPLE","Iphone");
TechCompany *tecCompany = company;
delete company;
删除的时候,因为 *company 和 *tecCompany 这两个指针指向的是同一块内存,所以删除一个就ok啦,准确的说应该是回收,回收指向的那个地址位置的内存。