C++ 中的内联虚函数
C++ 中的虚函数用于创建基类指针列表,并调用任何派生类的函数,而无需了解派生类对象的类型。虚函数在运行时进行后期解析。
虚函数的主要用途是实现运行时多态性。内联函数用于提高代码效率。每次调用内联函数时,在编译时,内联函数的代码替换为内联函数调用点。
无论何时使用基类引用或指针调用虚函数,都不能内联此函数,但是,如果使用不带该类的引用或指针调用对象,则可以内联,因为编译器在编译时知道对象的精确类。
示例代码
#include<iostream>
using namespace std;
class B {
public:
virtual void s() {
cout<<" In Base \n";
}
};
class D: public B {
public:
void s() {
cout<<"In Derived \n";
}
};
int main(void) {
B b;
D d; // An object of class D
B *bptr = &d;// A pointer of type B* pointing to d
b.s();//Can be inlined as s() is called through object of class
bptr->s();// prints"D::s() called"
//cannot be inlined, as virtualfunction is called through pointer.
return 0;
}输出
In Base In Derived
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP