C++ Virtual Function-Can a static function be a virtual function

1.virtual and static functions

C++中,静态成员函数不能被声明为virtual函数。

例如,下面的程序会编译失败。

class Test
{
  public:
     // 编译错误:static成员函数不能声明为virtual   
     virtual static void fun()  { }
};

同样地,静态成员函数也不能被声明为const和volatile.
下面的程序也会编译失败。

class Test
{
   public:
      // 编译错误: static成员函数不能为const
      static void fun() const { }
      // 如果声明为下面这样,是可以的。
      const static void fun() {}
      或类似于
      const static int fun() { return 0; }
};

2. Why static member functions cannot be virtual

  1. Static members do not belong to any class object or class instance, so even adding virtual to this function is meaningless.

  2. There is one major difference between static and non-static member functions. That is, static member functions do not have this pointer.

 虚函数依靠vptr和vtable来处理。vptr是一个指针,在类的构造函数中创建生成,并且只能用this指针来访问它,因为它是类的一个成员,并且vptr指向保存虚函数地址的vtable.

 对于静态成员函数,它没有this指针,所以无法访问vptr. 这就是为何static函数不能为virtual.

 虚函数的调用关系:this -> vptr -> vtable ->virtual function

      3. Through the following example, it can be determined that when a virtual function is added to the class, the size of the class will increase by 4 bytes (the size of the pointer).

class Test
{
public:
int _m;
};
sizeof(Test) = 4;

加入虚函数后,

class Test
{
public:

int _m;
virtual void fun();
};
sizeof(Test) = 8

4. Why static member functions cannot be const functions

 当声明一个非静态成员函数为const时,对this指针会有影响。对于一个Test类中的const修饰的成员函数,this指针相当于const Test*, 而对于非const成员函数,this指针相当于Test *.

 而static成员函数没有this指针,所以使用const来修饰static成员函数没有任何意义。

 volatile的道理也是如此。

 

Guess you like

Origin blog.csdn.net/sunlin972913894/article/details/103653271