我们可以访问纯虚拟类的静态成员变量吗?

can we access static member variable of pure virtual class?

本文关键字:静态成员 变量 虚拟 访问 我们      更新时间:2023-10-16

请考虑以下代码:

#include<iostream>
/* pure virtual class*/
class cTest {
    public:
        cTest(void);
        static void sFuncG(void);
        static void sFuncS(int);
        virtual void vFunc(void) = 0;
    private:
        static int  sVar;
};
/*the constructor dose nothing meaningful*/
cTest::cTest(void)
{
    return;
}
/*there are two static function who needs to access the static member variable*/
void cTest::sFuncS(int num)
{
    sVar = num;
}
void cTest::sFuncG(void)
{
    std::cout<<sVar<<std::endl;
}
/*the derived class*/
class cDrvd : public cTest {
    public:
        cDrvd(int);
        virtual void vFunc(void);
    private:
        int mem;
};
cDrvd::cDrvd(int num)
{
    mem = num;
}
void cDrvd::vFunc(void)
{
    cTest::sFuncS(mem);
}
int main()
{
    cDrvd myClass(5);
    cTest::sFuncG();
    return 0;
}

当我尝试构建代码时,出现链接器错误:

me@My-PC:MyTestProgs$ g++ -o testStatic testStatic.cpp 
/tmp/ccgUzIGI.o: In function `cTest::sFuncS(int)':
testStatic.cpp:(.text+0x22): undefined reference to `cTest::sVar'
/tmp/ccgUzIGI.o: In function `cTest::sFuncG()':
testStatic.cpp:(.text+0x2e): undefined reference to `cTest::sVar'
collect2: error: ld returned 1 exit status

我在大型代码中发现了问题,并尝试在我的上述代码中重现它。

我的理解是:

  • 静态成员变量是在创建类的第一个实例时创建的。
  • 此处,不会创建类 cTest 的实例,因此不存在静态成员变量 sVar
  • 由于类 cTest 是纯虚拟的,我们无法创建它的实例。所以我们无法访问sVar.

我对 c++ 相当陌生,记住这一点,有人可以确认我的理解吗?

如果是这种情况,这种情况的解决方法是什么?

你必须定义静态成员

    static int  sVar;

独立于实现文件中的类。

int cTest::sVar = 0;  //initialization is optional if it's 0.

至于您的问题:-

Q1) static member variables are created when the 1st instance of the class is created.

即使没有创建类的实例,也没有静态成员。

Q2) Here, no instance of class cTest is created, so the static member variable sVar 
is not present.

如上所述,静态成员变量将在那里。

Q3)As the class cTest is pure virtual, we can not create an instance of it. 
So we cannot access sVar.

您可以访问sVar,例如 cTest::sVar .