📜  C++中虚函数和内联函数的区别

📅  最后修改于: 2021-09-13 03:08:26             🧑  作者: Mango

虚拟函数: 虚函数是在基类中声明并由派生类重新定义的成员函数。

内联函数: 内联函数是一个普通的函数,由关键字 inline 定义,它是一个由编译器扩展的短函数,它的参数只被评估一次。

在 C++ 中定义内联函数的语法是:

inline return-type function-name(parameters)
{
    // function code
} 

虚函数和内联函数的区别如下:

Virtual function

Inline function

1. Virtual function must be declared in public section of class. 1. Inline function is a normal function which is defined by the keyword inline.
2. Virtual function cannot be static. 2. Inline function can also be non-static.
3. Virtual function is defined in base class. 3. Inline function are the short length functions that are automatically made the inline functions without using the inline keyword inside the class.
4. Virtual function are decrease the efficiency of code. 4. Inline function are used to increase the efficiency of code.
5. Virtual function is to run time polymorphism. 5. Inline function is to compile time polymorphism.
6. Virtual function may consists of virtual destructor but it cannot have a virtual constructor.  6. Inline function can also consist of inline constructor.
7. Virtual may use for dynamic linkage. 7. Inline function is used to reduce the function call overhead.
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程