Some interesting facts about static member functions in C++

 

  

  在C++中,类的静态成员函数有以下几点需要注意:

  (1)静态成员函数没有this指针

  例如,下面的程序有编译错误"`this’ is unavailable for static member functions"。

 1 #include<iostream>
 2 class Test 
 3 {      
 4    static Test * fun() 
 5    {
 6         return this; // compiler error
 7    }
 8 };
 9   
10 int main()
11 {
12    getchar();
13    return 0;
14 }

 

  (2)静态成员函数不可能为virtual 函数

  例如,下面的程序会有编译错误。

 1 #include<iostream>
 2  
 3 using namespace std;    
 4   
 5 class Test
 6 {
 7    public:
 8       // Error: Virtual member functions cannot be static      
 9       virtual static void fun()  
10       { 
11       }
12 };

  

  (3)具体相同的函数名和相同的函数参数列表不能构成重载,若其中任何一个函数是static成员函数。

  例如,下面的程序会发生编译错误"‘void Test::fun()’ and `static void Test::fun()’ cannot be overloaded"。

 1 #include<iostream>
 2 class Test 
 3 {
 4    static void fun() 
 5    {
 6    }
 7    void fun()     // compiler error
 8    {
 9    } 
10 };
11   
12 int main()
13 {
14    getchar();
15    return 0;
16 }

 

  (4)静态成员函数不可能声明为const、volatile和const volatile。

  具体解释如下图所示。

  

  例如,下面的程序会发生编译错误"static member function `static void Test::fun()’ cannot have `const’ method qualifier"。

 1 #include<iostream>
 2 class Test 
 3 {      
 4    static void fun() const 
 5    { 
 6         // compiler error
 7         return;
 8    }
 9 };
10   
11 int main()
12 {
13    getchar();
14    return 0;
15 }

 

  References:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf

  

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  08:49:18

 

 

原文地址:https://www.cnblogs.com/iloveyouforever/p/3442614.html