delete基类指针能不能释放子类对象

#include <stdio.h>

class A
{
public:
	A() { printf("A\n"); }
	~A() { printf("~A\n"); }
};

class B : public A
{
public:
	B() { printf("B\n"); }
	~B() { printf("~B\n"); }
};

int main()
{
	A *p = new B;
	delete p;
	return 0;
}

执行结果:

A
B
~A

基类析构函数加上virtual再试试

#include <stdio.h>

class A
{
public:
	A() { printf("A\n"); }
	virtual ~A() { printf("~A\n"); }
};

class B : public A
{
public:
	B() { printf("B\n"); }
	~B() { printf("~B\n"); }
};

int main()
{
	A *p = new B;
	delete p;
	return 0;
}

执行结果:

A
B
~B
~A

 

如果基类的析构函数不是虚函数,那么delete基类指针不能释放子类对象,不会调用子类对象的析构函数,这种做法是不完善的。

如果基类的析构函数是虚函数,那么delete基类指针是可以调用子类对象的析构函数的。

 

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,下面是代码实现: ```c++ #include <iostream> #include <string> using namespace std; class Role { protected: string name; int age; char gender; public: Role() {} Role(string n, int a, char g) : name(n), age(a), gender(g) {} void setName(string n) { name = n; } void setAge(int a) { age = a; } void setGender(char g) { gender = g; } string getName() const { return name; } int getAge() const { return age; } char getGender() const { return gender; } virtual void display() const { cout << "Name: " << name << ", Age: " << age << ", Gender: " << gender << endl; } }; class Employee : public Role { private: int id; double salary; public: Employee() {} Employee(string n, int a, char g, int i, double s) : Role(n, a, g), id(i), salary(s) {} Employee(const Role& r, int i, double s) : Role(r), id(i), salary(s) {} void setId(int i) { id = i; } void setSalary(double s) { salary = s; } int getId() const { return id; } double getSalary() const { return salary; } void display() const override { Role::display(); cout << "ID: " << id << ", Salary: " << salary << endl; } }; int main() { Role* p = new Employee("John", 30, 'M', 1001, 5000); p->display(); delete p; return 0; } ``` 运行结果: ``` Name: John, Age: 30, Gender: M ID: 1001, Salary: 5000 ``` 在这个程序中,我们首先定义了一个基类 `Role`,它包含了姓名、年龄、性别三个数据成员以及相应的读写函数和一个虚函数 `display()`。然后我们从 `Role` 派生出了一个名为 `Employee` 的,它额外包含了两个数据成员 `id` 和 `salary`,同时重新定义了虚函数 `display()`。在 `main()` 函数中,我们定义了一个基类指针 `p` 并将其指向一个 `Employee` 对象,然后通过这个指针调用 `display()` 函数,由于 `display()` 是虚函数,因此会调用 `Employee` 中的版本。最后别忘了释放内存。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值