2016-11-13 121 views
0

對不起提前如果這是一個愚蠢的或無義的問題,而是:C++訪問類的靜態成員變量,沒有朋友

可用於一類非恆定的靜態類變量被另一個類使用沒有使用朋友或基地/派生類?在(略)情況是:

class Decl { 
    public: 
      static string searchVal; 
      ... (other irrelevant stuff) 
}; 

class Conj { 
    public: 
     static string searchVal; 
     ... (other irrelevant stuff) 
}; 

我不想重複searchVal兩個班,因爲程序的其餘部分,我並不熱衷於使用的朋友(但我會當它是唯一的選擇)。

+0

您可以訪問任何地方使用'::申報的searchVal'靜態成員 – pat

回答

0

由於您static成員public,如果你的類定義都是可見的,那麼它們的靜態成員可以分別以Decl::searchValConj::searchVal訪問。

例如

class Decl 
{ 
    public: static string searchVal; 
}; 

class Conj 
{ 
    public: 
     static string searchVal; 
}; 

// within ANY function, including members of either class above 
// ... as long as both definitions above are visible to the compiler 

if (Conj::searchVal == Decl::searchVal) 
{ 
     // do something 
}