MyH.h
class StaticConst
{
public:
StaticConst()// :abc(0) -----(1)error C2438: 'abc' : cannot initialize static class data via constructor
{
//abc = 0; -------(2) error: expression must be a modifiable lvalue
}
void Tell();
private:
static int const abc ;//= 45; -------(3)
};
MyH.cpp
#include "MyH.h"
#include <iostream.h>
//const int StaticConst::abc ;//= 40;-------(4)
void StaticConst::Tell()
{
cout<<abc<<endl;
}
void main()
{
StaticConst sc;
sc.Tell();
}
1,2皆错误, 3,4方式选择一个即可,其中方式3在vc6下不行,使用intel编译器可以
--------------------------------------------------------------------------------------
class NoDefFunc
{
public:
static int GetInt();
enum { value = sizeof (GetInt()) };
};
void main()
{
cout<< NoDefFunc::value<<endl;
}
Output: 4
static成员函数甚至不需要有函数定义,声明即可
本文探讨了C++中静态成员变量的正确初始化方法,并通过具体示例展示了不同初始化方式的效果及编译器反应。同时,文章还讨论了静态成员函数的使用特点。
1906

被折叠的 条评论
为什么被折叠?



