类里面的const:编译期间的变量和常量

 //类里面的const:编译期间的变量和常量。
#include<iostream>
#include<string>
using namespace std;
//var in compile-time:
class Fred {
      const int size;
public:
       Fred(int sz);
       void print();
};
//对size的初始化在参数列表和函数体之间,保证在使用它之前为常量。
Fred::Fred(int sz):size(sz){}
void Fred::print(){ cout << size << endl; }
//constant in comiple-time:
//一个存放字符串指针的栈StringStack:
class StringStack{
 //keyword:static
         static const  int size = 100;//enum {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* t = stack[--index];
              stack[index] = 0;
              return t;
 }
       return 0;
}
//StringStack测试用例:
string iceCream[] = {
          "pralines & cream",
         "fudge ripple",
         "wild mountain",
         "raspberry sorbet",
         "rocky road"
};
//calculat the size of the case:
 const int iCsz =
       sizeof iceCream / sizeof *iceCream;
//Test in main():
int main(){
 //class Fred:
  Fred a(1),b(2),c(3);
  a.print(),b.print(),c.print();
  //class StringStack:
  StringStack ss;
 for(int i = 0; i < iCsz; ++i)
       ss.push(&iceCream[i]);
 const string* p;
 while((p = ss.pop()) != 0)
       cout << *p << endl;
 //display the result
  system("pause");
 }
/** 对对象的数组初始化的三种方法
 @for循环
 @构造函数
 @<string.h>的memset(,,)【该函数以字节为操作单位】
 */

你可能感兴趣的:(c,String,测试,System,Class)