class mystr
{
private:
public:
static const int strNum;
mystr();
CString m_str[strNum];};const int mystr::strNum=10;各们这样为什么不可以?strNum不是在定义类的时候就分配全局内存了吗??
{
private:
public:
static const int strNum;
mystr();
CString m_str[strNum];};const int mystr::strNum=10;各们这样为什么不可以?strNum不是在定义类的时候就分配全局内存了吗??
#include <string>
using namespace std;class A
{
public:
static const int i;
A();
private:
};
const A::i=12;//类变量要在类外边初始化
A::A()
{
};
void main()
{
}
可以编辑的时候有错误,主要是 CString m_str[strNum]; 这里,用这个静态常量定义数组的个数
CString m_str[strNum];
放在
const int mystr::strNum=10;
之后就可以了。也就是说,在编译的时候,一定要初始化在前,使用在后。
class mystr
{
private:
public:
static const int strNum = 10;
mystr();
CString m_str[strNum];};
出了很多错误, : error C2258: illegal pure syntax, must be '= 0'
: error C2252: 'strNum' : pure specifier can only be specified for functions
: error C2065: 'strNum' : undeclared identifier
: error C2057: expected constant expression
: warning C4200: nonstandard extension used : zero-sized array in struct/union
: error C2039: 'strNum' : is not a member of 'mystr'
: see declaration of 'mystr'
constTest.cpp
: error C2258: illegal pure syntax, must be '= 0'
: error C2252: 'strNum' : pure specifier can only be specified for functions
: error C2065: 'strNum' : undeclared identifier
: error C2057: expected constant expression
: warning C4200: nonstandard extension used : zero-sized array in struct/union
Generating Code...
Error executing cl.exe.
Creating browse info file...dlg.exe - 9 error(s), 2 warning(s)
const int strNum = 10;//或者这样 #define strNum 10
class mystr
{
private:
public:
mystr();
CString m_str[strNum];};
这样是可以的,但这就定义成全局变量了,
class mystr
{
private:
enum{e1=10,e2=20};
public:
mystr();
CString m_str[e1];
};
这样也可以
现在的目的就是想定义为这个类的静态常量,只在类内作用范围。
如果是的话mystr::strNum用
改成CStringArray m_strArr;吧
static const int 可以的
const int 好像也不可以的。
const int的初始化也不能放在类的定义中,只能放在初始化列表中。
老大,不知道就不要乱说了。static 成员变量,不可以在类的定义中初始化,不管是 static int 还是static const int。
头文件会被包含很多次,相当于会有很多重定义!
2。常量作为数组大小应该是可行的。
3。类声明里面,常量使用先于声明应该可行。至少VC可以。
你想这样啊,那真是没有办法了。
首先,不能在类的声明里面为变量初始化。如果是这样,倒是可以:
class CA
{
public: static const int s_i; void Func();
protected:
private:
};const int CA::s_i = 10;void CA::Func()
{
int arrI[s_i];
}不过想用静态整形常量作为其他数组类型的成员变量的下标,我不知道怎样才能在使用之前初始化它。这条路行不通,建议使用其他方法吧。
您说的,和我现在了解的基本差不多:
1)类定义内不可以初始化static 、const、static const成员变量
2)想用类的静态常量成员 作为其他数组类型的成员变量的下标,实在不可行。感觉他们的初始化相冲突,初始化这个了那个没初始化。
3)可以使用 enum实现这个想法。