【问题标题】:Declaring a variable inline with an assignment c++使用赋值 c ++ 内联声明变量
【发布时间】:2012-09-03 16:42:55
【问题描述】:

在阅读 C++ 中的位图处理时,我遇到了这段代码 用于使用从位图文件中获取的数据加载调色板:

//set Number of Colors
numColors = 1 << bmih.biBitCount;

//load the palette for 8 bits per pixel
if(bmih.biBitCount == 8) {
        colours=new RGBQUAD[numColours];
        fread(colours,sizeof(RGBQUAD),numColours,in);
}

其中“bmih.biBitCount”是一个已经有值的预定义变量。 为什么作者声明 numColors 等于 1 然后将值 bmih.biBitCount 分配给同一行中的该变量?这到底是做什么的?像这样为变量赋值两次有什么好处?

【问题讨论】:

  • 1 没有像你想的那样分配给numColors
  • 你真的需要一本 C++ 入门书

标签: c++ variables syntax bitmap inline


【解决方案1】:

为什么作者声明 numColors 等于 1 然后在同一行中将值 bmih.biBitCount 分配给该变量?

他没有;他将表达式1 &lt;&lt; bmih.biBitCount 的结果分配给numColors。分配最后发生。 &lt;&lt;bitwise left shift operator。这样想:

//set Number of Colors
numColors = (1 << bmih.biBitCount);

【讨论】:

  • 所以 (1
  • @bjh:不。请点击有关按位移位运算符的链接。
【解决方案2】:

他没有,这是一个使用 &lt;&lt; 作为“流”操作符的情况,会让人感到困惑。

&lt;&lt;&gt;&gt; 运算符传统上是位移运算符,这就是它们在这种情况下的含义。这些运算符将变量左移或右移多个位置。假设我们有x = 0b00001(并且您的编译器可以理解这样的二进制符号)。 x &lt;&lt; 2 将给出结果0b00100

【讨论】:

  • 1 &lt;&lt; bmih.biBitCount 表示将 1 按位左移 'bmih.biBitCount, which is, most probably zero. I guess bmih.biBitCount
  • @Lorlin - 不,它没有。 1 将被转换为numColors 的类型,然后左移 bmih.biBitCount。
  • 是的。对于任何 n!=0,1 左移 n 为零。不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2011-01-11
  • 1970-01-01
  • 2016-01-30
  • 2020-01-08
  • 1970-01-01
相关资源
最近更新 更多