2017-09-27 165 views
0
/*In header file */ 
class abc{ 
public: 
static bool do_something(); 

} 

/*In other file */ 
static bool isvalid=false; //global variable 

bool abc::do_something() 
{ 
return isValid; 
} 

它编译的很好。我想知道它是否正确使用?一个类的静态函数可以访问全局静态变量吗?

+1

这是合法的C++。它是否“正确”取决于问什么时候认为正确。 – StoryTeller

+0

当然是合法的。 –

+2

是的,它在技术上是正确的,但可能是糟糕的设计。 – alain

回答

0

是的,这是正确的 - 没有符号isvalid,其他文件将无法看到它。他们可以通过调用abc::do_something()

来读取它的当前值。成员函数不需要是静态的。所有的情况下,将能够返回isValid

相同的电流值在C++是让私人和在类的静态隐藏数据的正常方式...

头文件

class abc{ 
    static bool isValid; // can be seen, does not use space in an instance 
public: 
    static bool do_something(); 

} 


/*In other file */ 
bool abc::isvalid=false; //global variable 

bool abc::do_something() 
{ 
    return isValid; 
} 
相关问题