【发布时间】:2014-04-11 02:51:28
【问题描述】:
我对类中的静态和静态 const 变量有疑问。
特别好奇关于static和static const的内存状态。
在下面的代码中,
#include <iostream>
using namespace std;
class test{
public:
static const int testConstStatic =1;
static int testStatic;
};
int test::testStatic = 0;
int main(){
cout << test::testStatic << endl;
cout << test::testConstStatic << endl;
return 0;
}
为什么需要使用“静态 int testStatic”定义,如果不需要,我得到关于 testStatic 的“未定义参考”?
这个定义是否与 testStatic 建立联系?
那么 testConstStatic 呢?
提前致谢!
已更新!!
这个问题的主要原因是,当我将静态变量声明为肯定没有定义的全局变量并打印输出时,没有关于“未定义引用”的消息,但是对于没有定义的 CLASS 中的静态变量,它显示消息“未定义引用”
#include <iostream>
using namespace std;
static int testStaticInGlobal;
class test{
public:
static int testStatic;
};
int test::testStatic = 0;
int main(){
cout << test::testStatic << endl; // 'Undefined reference' error without definition
cout << testStaticInGlobal << endl; // no error without definition
return 0;
}
谢谢!
【问题讨论】:
-
什么是
static const?只需const就足够了 -
@EdHeal +1 到评论,还有例外情况。前任。一个 DefaultValue 常量(例如
static const char[]),将 按地址 与成员进行比较,以确定是否在执行永不为空的ptr 策略时对其进行动态释放。诚然很少见,但确实发生了,除此之外,我完全同意你的看法,尤其是在似乎是 OP 的情况下。 (尽管现在我想到了我,我看到的每个示例都通过强制转换 const 来打破所有规则)。 -
随着你的更新,
static int testStaticInGlobal;是一个定义,而static int testStatic;不是因为它在一个类中。 -
@chris 好吧,看起来是这样,但只是因为它在课堂上?
-
@HwanghoKim,是的,这就是它的要点。我认为这与这样一个事实有关,即如果它是一个定义,那么您很容易遇到多个定义。