我有这个来自C++ primer第5版的例子。ch-19位字段:
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)看起来毫无意义。
你认为如何?
发布于 2021-08-31 22:39:35
mode字段不会被视为位掩码,modes类型也不会定义2的幂的值。因此,您不应该使用逐位操作来设置/查询mode,正是由于这个原因,EXECUTE与READ和WRITE共享位,这与您希望每个模式独立的愿望背道而驰。在适当的位掩码中,EXECUTE应该定义为4 (二进制形式的100),而不是3。
https://stackoverflow.com/questions/69005905
复制相似问题