Dip*_*pto 1 c++ virtual static
请考虑以下代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试构建代码时,出现链接器错误:
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
Run Code Online (Sandbox Code Playgroud)
我在一个大代码中发现了这个问题,并试图在我上面的代码中重现它。
我的理解是:
cTest创建类的实例,因此sVar不存在静态成员变量。sVar.我对 c++还很陌生,记住这一点,有人请确认我的理解吗?
如果是这种情况,这种情况的解决方法是什么?
你必须定义静态成员
static int sVar;
Run Code Online (Sandbox Code Playgroud)
独立于实现文件中的类。
int cTest::sVar = 0; //initialization is optional if it's 0.
Run Code Online (Sandbox Code Playgroud)
就您的问题而言:-
Q1) static member variables are created when the 1st instance of the class is created.
Run Code Online (Sandbox Code Playgroud)
即使没有创建类的实例,也没有静态成员。
Q2) Here, no instance of class cTest is created, so the static member variable sVar
is not present.
Run Code Online (Sandbox Code Playgroud)
如上所述,静态成员变量将在那里。
Q3)As the class cTest is pure virtual, we can not create an instance of it.
So we cannot access sVar.
Run Code Online (Sandbox Code Playgroud)
您可以sVar像cTest::sVar.
| 归档时间: |
|
| 查看次数: |
779 次 |
| 最近记录: |