网站首页 > 基础教程 正文
C++的虚构函数可以定义为虚函数,这个在类需要继承的时候是至关重要的。
比如:
#include <iostream>
using namespace std;
class Base {
public:
void hello() {
cout << "helloworld" << endl;
}
};
class Derived: public Base {
public:
Derived(): Base() {
}
~Derived() {
cout << "Derived destructor." << endl;
}
};
int main() {
Base* pBase = new Derived();
pBase->hello();
delete pBase;
return 0;
}
可以看到,Base class没有定义析构函数函数,当我们delete的时候使用Base的指针的时,Derived类的析构函数不会被调用。
现在我们定义一个析构函数:
class Base {
public:
void hello() {
cout << "helloworld" << endl;
}
~Base() {
cout << "Base destructor" << endl;
}
};
运行结果如下,可以看到Base的析构函数确实被调用了,但是Derived析构函数还是没有调用。
最好我们把析构函数申明为虚函数:
class Base {
public:
void hello() {
cout << "helloworld" << endl;
}
virtual ~Base() {
cout << "Base destructor" << endl;
}
};
这次才真正把子类的析构函数给调用了:
所以在C++语言里面,如果没有特殊原因,还是建议把析构函数定义为虚函数。
猜你喜欢
- 2024-11-12 金三银四不跳槽更待何时?安卓开发1年字节5面面经,已成功上岸
- 2024-11-12 C++要学到什么程度才能找到实习? c++学完学什么
- 2024-11-12 C++基础语法梳理:inline 内联函数!虚函数可以是内联函数吗?
- 2024-11-12 C++基类中虚析构函数 c++ 虚析构函数
- 2024-11-12 C和C++代码精粹:C语言和C++有什么区别么?
- 2024-11-12 3个面试C++开发岗位的高频笔试题 c++软件开发面试
- 2024-11-12 一文在手,"类间关系"不再困惑
- 2024-11-12 c++的面试总结 c++面试知识点
- 2024-11-12 C++ 虚函数 实例学习 简单易懂 c++虚函数的使用
- 2024-11-12 C++虚函数会导致性能开销大? c++虚函数使用
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)