请考虑以下代码:
#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
。sVar
。我对c ++ 相当陌生,保持这种想法,有人请证实我的理解吗?
如果是这种情况,那么情况的解决方法是什么?
答案 0 :(得分:4)
您必须定义静态成员
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
。