我们可以访问纯虚拟类的静态成员变量吗?
can we access static member variable of pure virtual class?
请考虑以下代码:
#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
.
相关文章:
- C++:是否可以使用非静态成员变量模板?
- 如何在复杂继承中访问静态成员变量
- 静态成员变量不会由 gettext 转换
- 为什么我不能像这样在静态成员函数中调用静态成员变量?
- C++ lambda - 捕获静态成员变量
- 多线程处理中的静态成员变量
- 纯标头库中静态成员变量的正确设置器和 getter
- 如何从具有专用化的类模板定义静态成员变量?
- 为什么可以在没有实例变量的情况下访问静态回调方法中的静态成员变量?
- 声明和定义类静态成员变量不会导致多重声明,这是为什么?
- 为什么不允许静态成员变量的初始化在类中,而允许静态静态成员的初始化
- 类中的静态成员变量和C++中的全局变量有什么区别?
- C++ 静态成员变量 - 文件之间的访问
- 如何在运行时使用静态成员函数初始化静态成员变量
- 模板类中嵌套类的C 静态成员变量
- 如何检查静态成员变量模板?
- 重载运算符和静态成员变量的行为
- 类的静态成员变量(受保护)的作用域
- gcc 和 clang 中 constexpr 静态成员变量的链接器错误
- dll 中静态成员变量的生存期