作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
请考虑以下代码:
#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++ 的新手,记住这一点,有人可以确认我的理解吗?
如果是这种情况,该情况的解决方法是什么?
最佳答案
你必须定义静态成员
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.
您可以像 cTest::sVar
一样访问 sVar
。
关于c++ - 我们可以访问纯虚类的静态成员变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27145523/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!