捷通华声一道面试题 base derived

本文通过C++代码示例介绍了基类与派生类中虚函数的应用及析构函数的重要作用,特别是当使用指向派生类对象的基类指针时,正确设置虚析构函数以确保资源被妥善清理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Base
{
private:
int Y;
public:
Base(int y = 0) { Y = y;cout << "Base(" << y << ")\n"; };
~Base() { cout << "~Base()\n"; };
virtual void print() { cout << Y << " "; };
};
class Derived : public Base
{
private:
int Z;
public:
Derived(int y, int z) :Base(y) { Z = z;cout << "Derived(" << y <<","<<z<<")\n"; };
~Derived() { cout << "~Derived()\n"; };
void print() { Base::print();cout << Z << endl; };
};
int main()
{
Derived d(300, 400);                     // Base(300) Derived(300,400)
d.print();             // 300 400


Base *a = new Derived(100, 200);              // Base(100) Derived(100,200)
a->print();       // 100 200
delete a;       // ~Base()            析构没有定义成virtual 所以无法调用子类的析构


// d的析构  // ~Derived() ~Base()

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值