static用法报错解决:cannot declare member function to have static linkage [-fpermissive](九十二)

后学
2023-12-01

static用法报错解决:cannot declare member function to have static linkage [-fpermissive] 

1.test.h 定义
class Test{
  static Test* GetInstance(); //.h文件中的Test类,加static属于Test类区域的范围
  static CameraHardwareInterface* mSelf; //.h文件中的Test类,加static属于Test类区域的范围
}


2.test.cpp实现
//错误用法  
static Test* Test::GetInstance(){//.cpp文件中加static属于test.cpp范围的域,和test.h文件中不是一
个定义的成员函数.                                                                                                                                                                                                                                                                        
  if(mSelf == NULL)                                                                                                                                                                                         
    mSelf = new Test;                                                                                                                                                                    
                                                                                                                                                                                                              
    return mSelf;                                                                                                                                                                                             
} 

正确用法:
Test* Test::GetInstance(){                                                                                                                                                                                                                                                                            
  if(mSelf == NULL)                                                                                                                                                                                         
    mSelf = new Test;                                                                                                                                                                    
                                                                                                                                                                                                              
    return mSelf;                                                                                                                                                                                             
}

注意:
static的意义:一个作用域的范围(仅限本文件内).
<1>.成员函数加static修饰的作用域是类域, 而在类外部加static不是表示静态函数,而是表示函数拥有本文件
域,而类的域是小于文件域,强行把类域扩大到文件域,就会出错。

 类似资料: