使用static const int size=100为什么会报错?

ljyshadow 2005-04-10 05:42:13
最近在学const的用法,在VC++上调试出现了点小问题:书上说enum{size=100}; 和 static const int size=100; 效果是一样的,为什么我在VC++上用前者可以通过,但用后者就会报错呢?有没有人知道为什么?代码如下:
#include<iostream>
#include<string>
using namespace std;
class StringStack
{
enum{size=100};//能够正常运行
//static const int size=100;//Error!显示5个错误
const string *stack[size];
int index;
public:
StringStack();
void push(const string *s);
const string *pop();
};
StringStack::StringStack():index(0)
{
memset(stack,0,size*sizeof(string*));
}
void StringStack::push(const string*s)
{
if(index<size)
stack[index++]=s;
}
const string *StringStack::pop()
{
if(index>0)
{
const string* rv=stack[--index];
stack[index]=0;
return rv;
}
return 0;
}
string icenu[]={"hello","the world","how much","thankyou","very good"};
const int icenum=sizeof icenu/sizeof *icenu;
void main()
{
StringStack ss;
for(int i=0;i<icenum;i++)
ss.push(&icenu[i]);
const string* cp;
while((cp=ss.pop())!=0)
cout<<*cp<<endl;

}
...全文
333 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
ljyshadow 2005-04-11
  • 打赏
  • 举报
回复
明白了,多谢高手指教!怎样把分给回答我的问题的人呢?
rainfall19831109 2005-04-10
  • 打赏
  • 举报
回复
const是常量了,不允许改变啊

要赋初值的话要全局赋值
swordkitty 2005-04-10
  • 打赏
  • 举报
回复
支持楼上
fanqing 2005-04-10
  • 打赏
  • 举报
回复
如楼上所说.类成员静态变量初始化比较特殊,需要在外部初始化.
cnwolf 2005-04-10
  • 打赏
  • 举报
回复
static const int size=100;//Error!显示5个错误

const 表示size是静态的,在执行期间,不允许在运行时改变值,在构造函数里初始化
const int size;

static 表示数据StringStack::StringStack():index(0)
{
memset(stack,0,size*sizeof(string*));
size = 100
}
保存在全局静态数据中,在函数外初始化

static int size;

StringStack::size = 100;
wbusy 2005-04-10
  • 打赏
  • 举报
回复
同意楼上的

类的静态成员应该全局初始化
0011411 2005-04-10
  • 打赏
  • 举报
回复
楼上的已经说的很清楚了,你初始化的地方不对!
mumutouv 2005-04-10
  • 打赏
  • 举报
回复
//static const int size=100;//Error!显示5个错误
这样肯定报错
在H文件中
static const int size;
在CPP文件中

int StringStack::size = 100;

oyljerry 2005-04-10
  • 打赏
  • 举报
回复
全局初始化

16,551

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Creator Browser
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧