首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++入门,第5版,第19位

C++入门,第5版,第19位
EN

Stack Overflow用户
提问于 2021-08-31 22:26:42
回答 1查看 68关注 0票数 1

我有这个来自C++ primer第5版的例子。ch-19位字段:

代码语言:javascript
复制
 typedef unsigned int Bit;
 class File {
     Bit mode: 2;       // mode has 2 bits
     Bit modified: 1;   // modified has 1 bit
     Bit prot_owner: 3; // prot_owner has 3 bits
     Bit prot_group: 3; // prot_group has 3 bits
     Bit prot_world: 3; // prot_world has 3 bits
     // operations and data members of File
 public:
     // file modes specified as octal literals; see § 2.1.3 (p. 38)
     enum modes { READ = 01, WRITE = 02, EXECUTE = 03 };
     File &open(modes);
     void close();
     void write();
     bool isRead() const;
     void setWrite();C++ Primer, Fifth Edition
 };

 File &File::open(File::modes m)
 {
     mode |= READ;    // set the READ bit by default
     // other processing
     if (m & WRITE) // if opening READ and WRITE
     // processing to open the file in read/write mode
     return *this;
 }

让我好奇的是:mode成员只是2 bits,所以它可以保存值:0, 1, 2, 3 (二进制形式的00 01 10 11 )。值3被定义为一个枚举,该枚举将打开模式指定为execute,但是如果在这里为execute打开它,那么它也将被打开以用于写入:3 & 2 = 2 3 & 1 = 1,我认为这是一个错误。通常,每种模式都独立于任何其他模式。

我的意思是,例如,在成员函数open()中,mode |= READ可以设置第一个读取位。现在,如果用户已经打开文件以执行3 (二进制形式的11),则if(m & WRITE)看起来毫无意义。

你认为如何?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-31 22:39:35

mode字段不会被视为位掩码,modes类型也不会定义2的幂的值。因此,您不应该使用逐位操作来设置/查询mode,正是由于这个原因,EXECUTEREADWRITE共享位,这与您希望每个模式独立的愿望背道而驰。在适当的位掩码中,EXECUTE应该定义为4 (二进制形式的100),而不是3

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69005905

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档