当前位置:编程学习 > C/C++ >>

关于C++编译期间类里的常量问题

#include "stdafx.h"
#include<iostream>
using namespace std;

class StringStack
{
 static const int size=100;
 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 iceCream[]={
 "praline & cream",
 "fudge ripple",
 "jamocha alnond fudge",
 "wild monutain blackberry",
 "raspberry storbet",
 "iemon swirl",
 "rocky road",
 "deep chocolate fudge"
};
const int iCsz=
 sizeof iceCream/sizeof*iceCream;

int _tmain(int argc, _TCHAR* argv[])
{
 StringStack ss;
 for(int i=0;i<iCsz;i++)
  ss.push(&iceCream[i]);
 const string*cp;
 while((cp=ss.pop())!=0)
  cout <<(const string) *cp<<endl;
 return 0;
}

 

stringstack\stringstack.cpp(62): error C2679: 二进制“<<”: 没有找到接受“std::basic_string<_Elem,_Traits,_Ax>”类型的右操作数的运算符(或没有可接受的转换)
1>          with

追问:这样改程序可以调试通过,但输出的是地址值,程序目的要输出地址所指向的值,为什么用cout<<*p<<ednl;是不对的那?
答案: static const int size=100;

这句是错.的.不能在类里边赋static数据成员的初值
必须在类外才能对static成员赋值.
在类外这样写:const int StringStack::size=100;

const string* stack[size];
这句会导致错误,因为size不确定,虽然你定义为const,但在类中不能这样使用。

总的说,程序组织有错误;
可以像下面这样来;
static const int size=100;
class StringStack
{
 const string* stack[size];

...

即将static const int size=100;这句提到类外面去


“<<”的错误是因为string是自定数据类型,cout无法进行自动转换。

 

当然,编译器不同可能出现不同的错误,你的编译器可能只出现"<<"的错误,我的是VC6,出现了上述三个错误。


 

#include<iostream>
你要+.h阿

应该是

#include<iostream.h>

上一个:谭浩强写过c++的书吗?
下一个:給我推薦本C++入門的書籍?

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,