虚方法、new和delete

版权声明:根号v587版权所有 https://blog.csdn.net/hcmdghv587/article/details/81911807
#include <iostream>
#include <string>
using namespace std;
class Company
{
public:
    Company(string);
    virtual ~Company();
    virtual void work(void);
protected:
    string name;
};
class TechCompany : public Company
{
public:
    TechCompany(string, string);
    ~TechCompany();
    void work(void);
private:
    string product;
};

Company::Company(string name)
{
    this -> name = name;
    cout << name << "公司诞生了!" << endl;
}
Company::~Company()
{
    cout << name << "公司倒闭了!" << endl;
}
TechCompany::TechCompany(string name, string product) : Company(name)
{
    this -> product = product;
    cout << name << "科技公司诞生了!" << endl;
}
TechCompany::~TechCompany()
{
    cout << name << "科技公司倒闭了!" << endl;
}
void TechCompany::work(void)
{
    cout << name << "公司开始工作了,生产了" << product << "产品。" << endl;
}
void Company::work(void)
{
    cout << name << "公司开始工作了!" << endl;
}

int main()
{
    Company *company;
    company = new Company("Microsoft");
    company -> work();
    delete company;

    company = new TechCompany("Apple", "Phone");
    company -> work();
    delete company;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hcmdghv587/article/details/81911807