header、body 和 derived class 中的虚函数是如何工作的?
How do virtual functions work in the header, body and derived class?
我正在努力掌握如何使用虚函数。
以下说法正确吗?我也不会在 base 的 .cpp 文件中包含虚拟吗?
并且在定义派生class时,是否还要在派生class的public中声明虚函数?
//BASE HEADER FILE
#ifndef BASE_H
#define BASE_H
class Base {
public:
virtual double testFunc() = 0;
int func2();
};
#endif
//BASE.CPP FILE
#include "base.h"
int Base::func2()
{
return 5;
}
//DERIVED HEADER FILE
#ifndef DER_H
#define DER_H
#include "base.h"
class Derived : public Base {
public:
double testFunc();
};
#endif
//DER.CPP FILE
#include "Der.h"
double Derived::testFunc()
{
return 3.2;
}
您不需要将 virtual
附加到已在父 class 中声明为虚拟的函数。 virtual
说明符指定 non-static 成员函数是虚拟的并且支持动态调度。它只能出现在 non-static 成员函数的初始声明的 decl-specifier-seq
中(即,当它在 class 定义中声明时)。
什么是虚函数
虚函数是在基 class 中声明的成员函数,并被派生 class re-defined(覆盖)。当您使用指针或对基 class 的引用来引用派生 class 对象时,您可以为该对象调用虚函数并执行派生 class 的版本功能。
虚函数的工作(VTABLE和VPTR的概念)
如果 class 包含虚函数,那么编译器本身会做两件事:
- 如果 class 的对象被创建,则虚拟指针 (VPTR) 作为 class 的数据成员被插入以指向 class 的 VTABLE。对于每个创建的新对象,都会插入一个新的虚拟指针作为该 class.
的数据成员
- 无论是否创建对象,一个称为 VTABLE 的静态函数指针数组,其中每个单元格包含 class 中包含的每个虚函数的地址。
关于虚函数的详细信息,已经有很多很好的答案了
How are virtual functions and vtable implemented?
我正在努力掌握如何使用虚函数。
以下说法正确吗?我也不会在 base 的 .cpp 文件中包含虚拟吗?
并且在定义派生class时,是否还要在派生class的public中声明虚函数?
//BASE HEADER FILE
#ifndef BASE_H
#define BASE_H
class Base {
public:
virtual double testFunc() = 0;
int func2();
};
#endif
//BASE.CPP FILE
#include "base.h"
int Base::func2()
{
return 5;
}
//DERIVED HEADER FILE
#ifndef DER_H
#define DER_H
#include "base.h"
class Derived : public Base {
public:
double testFunc();
};
#endif
//DER.CPP FILE
#include "Der.h"
double Derived::testFunc()
{
return 3.2;
}
您不需要将 virtual
附加到已在父 class 中声明为虚拟的函数。 virtual
说明符指定 non-static 成员函数是虚拟的并且支持动态调度。它只能出现在 non-static 成员函数的初始声明的 decl-specifier-seq
中(即,当它在 class 定义中声明时)。
什么是虚函数
虚函数是在基 class 中声明的成员函数,并被派生 class re-defined(覆盖)。当您使用指针或对基 class 的引用来引用派生 class 对象时,您可以为该对象调用虚函数并执行派生 class 的版本功能。
虚函数的工作(VTABLE和VPTR的概念)
如果 class 包含虚函数,那么编译器本身会做两件事:
- 如果 class 的对象被创建,则虚拟指针 (VPTR) 作为 class 的数据成员被插入以指向 class 的 VTABLE。对于每个创建的新对象,都会插入一个新的虚拟指针作为该 class. 的数据成员
- 无论是否创建对象,一个称为 VTABLE 的静态函数指针数组,其中每个单元格包含 class 中包含的每个虚函数的地址。
关于虚函数的详细信息,已经有很多很好的答案了 How are virtual functions and vtable implemented?