首页 > 试题广场 >

下面程序运行输出的结果是( ...

[不定项选择题]
下面程序运行输出的结果是(    ),不用考虑new失败的情况。
#include <stdio.h>
class CPerson{
public:
    virtual void Whoami() = 0;
};
class CStudent : public CPerson{
public:
    CStudent(){printf("student is created!\r\n");}
    virtual ~CStudent(){printf("student is destroy!\r\n");}
    virtual void Whoami(){printf("student!\r\n");}
};
class CTeacher : public CPerson{
public:
    CTeacher(){printf("teacher is created!\r\n");}
    virtual ~CTeacher(){printf("teacher is destroy!\r\n");}
    virtual void Whoami(){printf("teacher!\r\n");}
};
int main(){
    CPerson *pLily = new CTeacher();
    pLily->Whoami();
    delete (CTeacher *)pLily;
    CPerson *pLucy = new CStudent();
    pLucy->Whoami();
    delete pLucy;
return 0;
}
  • teacher is created!<div>teacher!</div><div>teacher is destroy!</div><div>student is created!</div><div>student!</div>
  • teacher is created!<div>teacher!</div><div>teacher is destroy!</div><div>student is created!</div><div>student!</div><div>student is destroy!</div>
  • teacher is created!<div>teacher!</div><div>student is created!</div><div>student!</div>
  • teacher!<div>student!</div>
int main()
{
CPerson *pLily = new CTeacher();//基类指针指向派生类  new 调用CTeacher类构造函数 打印teacher is created!
pLily->Whoami();                           //调用CTeacher类的whoami成员函数 打印teacher!
delete (CTeacher *)pLily;               //强制类型转换为Cteacher类指针 调用Cteacher类析构函数和抽象基类默认析构函数 打印                                                                                  //teacher is destroy!
CPerson *pLucy = new CStudent();
pLucy->Whoami();
delete pLucy;                                //调用抽象基类默认析构函数,无打印内容
return 0;
}
基类自定义析构函数结果如下:

编辑于 2019-08-28 18:28:15 回复(0)
基类的没有定义析构函数,所以是默认的析构函数(不是虚函数),所以delete pLucy调用的是基类默认的析构函数,没有输出:
student is destroy!

发表于 2020-08-10 15:27:17 回复(0)
感谢这个多选题😅
发表于 2023-09-17 14:43:09 回复(0)
这题的坑在于第21行,把基类指针强制转换为派生类指针
发表于 2022-05-11 11:54:19 回复(1)
利用父类指针指向子类对象。若父类析构函数不是虚函数,则delete目标是父类指针时,不会走子类的虚析构函数。若将其强转为子类的指针再进行delete,则会先走子类析构,再走父类析构。

发表于 2022-12-20 09:14:02 回复(1)
纯虚函数没有虚析构,指向子对象的父类指针,调用空析构。
发表于 2022-07-10 21:56:39 回复(0)
基类中没有虚析构函数
发表于 2023-10-15 14:54:17 回复(0)
基类的析构并非虚函数,所以delete pLucy;只析构基类
发表于 2023-07-25 14:22:12 回复(1)
父类指针可以开辟子类的内存,此时会有子类的属性开辟到堆区,如果父类中没有虚析构函数,父类指针是访问不到子类的析构函数的
发表于 2022-08-06 21:27:43 回复(0)
b
发表于 2021-06-18 13:39:34 回复(0)