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

来源:互联网 发布:php网络硬盘源码 编辑:程序博客网 时间:2024/05/17 09:07

//类里面的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(,,)【该函数以字节为操作单位】
 */

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/SearchLife/archive/2008/12/12/3502441.aspx

原创粉丝点击