c++访问静态类的成员变量,不是友

C++ access to static class member variables, not friend

本文关键字:变量 成员 访问 静态类 c++      更新时间:2023-10-16

如果这是一个愚蠢或无意义的问题,我很抱歉,但是:

一个类的非常量静态类变量可以在不使用友类或基类/派生类的情况下被另一个类使用吗?(缩写)情况如下:

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

我不想在两个类中重复searchVal,并且由于程序的其余部分,我不热衷于使用friend(但如果它是唯一的选择,我会使用它)。

因为你的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
 }