简体   繁体   English

C ++访问静态类成员变量,而不是朋友

[英]C++ access to static class member variables, not friend

I'm sorry in advance if this is a stupid or nonsense question, but: 如果这是一个愚蠢或胡说八道的问题,请您提前抱歉,但是:

Can a non-constant static class variable for one class be used by another class without using friend or base/derived classes? 一个类的非常量静态类变量可以在不使用友元或基类/派生类的情况下被另一类使用吗? The (abbreviated) situation is: (缩写)情况是:

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

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

I don't want to repeat searchVal in both classes, and because of the rest of the program, I'm not keen on using friend (but I will if it's the only option). 我不想在两个类中都重复执行searchVal,并且由于该程序的其余部分,我不热衷于使用friend(但是如果它是唯一的选择,我会的)。

Since your static members are public , if your class definitions are both visible, then their static members can be accessed using Decl::searchVal or Conj::searchVal respectively. 由于您的static成员是public ,如果你的类定义都是可见的,那么它们的静态成员可以使用访问Decl::searchValConj::searchVal分别。

For example 例如

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
 }  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM