Jane.T

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

布尔类型

==================================================

布尔类型对象可以被赋予文字值true或false。

当表达式需要一个算术值的时候,布尔对象和布尔文字都可以被隐式的提升为int:false变为0,true变为1。 例如:

bool found = false;

int occurrence_count = 0;

while (/*条件省略*/)

{

found = look_for();

occurrence_count += found;

}

如果有必要,算术值和指针值也能隐式地被转换为布尔类型的值。0或空指针被转换为false,所有其他的值都被转换成true。例如:

//返回出现次数

extern int find(const string& );

bool found = false;

if (found = find (“rosebud”))

   //ok: found == true

 

//如找到返回该项的指针

extern int* find (int value);

if (found = find(1024))

   //ok:found == true

 

 

枚举类型

===================================================

  • 枚举的定义:

        枚举类型用一个关键字enum,加上一个自定义的类型名来定义,类型名后面跟一个用花括号括起来的枚举成员列表,枚举成员之间用逗号隔开。

        缺省情况下,第一个枚举成员被赋以值0, 后面的每个成员一次比前面大1。

例如:

//shape == 0, sphere == 1, cylinder ==2, polygon == 3
enum Forms{ shape, sphere, cylinder, polygon };

      

    我们也可以在初始化时显示的给成员赋值,没有显式赋值的成员,其值仍旧是前一个成员加1.

例如:

//point2d == 2, point2w == 3, point3d == 3, point3w == 4
enum Points {point2d = 2, point2w, point3d = 3, point3w };

 

  • 枚举类型不仅定义了整数常量,而且还把它们组合成了一个集合。选择一个枚举类型对象作为函数的形参,可以限制传递的给函数的值只能是这个集合中的一个值。

例如:

//input, output, 和append是枚举成员

enum open_modes{ input = 1, output, append };

//open_modes是一个枚举类型

void open_file(string file_name, open_modes om);

  • 如果想要访问枚举成员的名字(如: input, output等),可以通过如下方式访问:

open_models om = append;

count << open_modes[input] << “ “ << open_modes[om] << endl;

输出为: input append

count << input << “ ” << om <<endl;

输出为: 1 3

  • C++不支持在枚举成员之间进行迭代,即不支持在枚举成员之间的前后移动。

 

  • 枚举对象的初始化: 枚举类型的对象只能被一个相同类型的枚举对象或相同类型的枚举成员初始化。 如下:
void mumble()
{
    enum Points {point2d = 2, point2w, point3d = 3, point3w };
    
    //ok: pt3d == 3
    Points pt3d = point3d;

    //ok:pt2w和pt3d都是Points的枚举类型
    Points pt2w = pt3d;

    //错误:pt2w被初始化为一个int整数
    //pt2w = 3;

    //错误:polygon不是Points的枚举成员
    //pt2w = polygon;
};
posted on 2010-02-15 17:27  Jane.T  阅读(741)  评论(0编辑  收藏  举报