为什么我的变量在应用位移运算符后没有更改?
Why hasn't my variable changed after applying a bit-shift operator to it?
int main()
{
int i=3;
(i << 1);
cout << i; //Prints 3
}
由于向左移动了一点,我本以为会得到6分。为什么它不起作用?
因为位移位运算符返回一个值。
你想要这个:
#include <iostream>
int main()
{
int i = 3;
i = i << 1;
std::cout << i;
}
轮班操作员没有"就地"轮班。你可能在考虑另一个版本。如果他们真的这样做了,就像许多其他C++二进制运算符一样,那么我们就会发生非常糟糕的事情。
i <<= 1;
int a = 3;
int b = 2;
a + b; // value thrown away
a << b; // same as above
您应该使用<<=
,否则值就会丢失。
您没有将表达式(i << 1);
的值赋值回i
。
尝试:
i = i << 1;
或者(相同(:
i <<= 1;
您需要将i
分配给移位后的值。
int main()
{
int i=3;
i <<= 1;
cout << i; //Prints 3
}
或者,您可以使用<lt;=作为分配操作员:
i <<= 1;
因为您没有将答案分配回i。
i = i << 1;
您需要使用i<<=1
(使用"左移和赋值运算符"(将值重新分配回i
原因:CCD_ 7产生中间值,该中间值不被保存回变量CCD_。
// i is initially in memory
int i=3;
// load i into register and perform shift operation,
// but the value in memory is NOT changed
(i << 1);
// 1. load i into register and perform shift operation
// 2. write back to memory so now i has the new value
i = i << 1;
出于您的意图,您可以使用:
// equal to i = i << 1
i <<= 1;
相关文章:
- 函数参数变量总是需要 & 或 * 运算符吗?
- 在未初始化的变量上使用复合赋值运算符(+=, ..)不是C++中的UB?
- 如何正确返回带有成员变量的重载运算符++?
- 如何在不使用赋值运算符的情况下为动态变量赋值?
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 变量地址的运算符[]是如何工作的
- 在C++中,为什么int可以使用new运算符初始化变量,而double不能
- 创建变量之间的运算符排列
- C++中重载复合赋值运算符不会更改变量
- 为什么通过通用引用运算符 (&&) 将变量的引用传递给 Varadic 模板函数失败?
- 为什么 ++ 运算符触发器返回对局部变量警告的引用
- 使用运算符将分隔的输入分隔>>变量
- 不太明白 & 运算符的地址在这个结构中做什么,以及它如何能够访问其他成员变量
- 为什么在 sizeof() 函数中与 * 运算符一起使用和不使用 * 运算符时,指向结构变量的指针大小会有所不同?
- 隐藏的成员变量不应在仅允许const访问的基类中突变,以便保留分配运算符
- 将删除运算符放置在何处以进行动态变量
- 重载运算符和静态成员变量的行为
- 为什么我的重载运算符+在向自身添加变量时会在返回时使"this"未初始化?
- 需要使用 Book* 头变量重载运算符,但不起作用
- 三元运算符:编译器不发出局部变量警告的返回引用