[英]variable declaration in while loop
using namespace std;
class Counter
{
int val;
public:
Counter() { val = 0; }
int Next() { return ++val; }
};
int main()
{
Counter counter;
while (int c = counter.Next() <= 5)
{
cout << c << endl;
}
}
When run, the program prints out 1
5 times.运行时,程序打印出
1
5 次。 Thus, .Next()
is returning the expected value as the while loop does terminate.因此,
.Next()
在 while 循环终止时返回预期值。
Why is the value of c
remain set to the initial value?为什么
c
的值仍然设置为初始值?
I'm very new to C++ (this is the first C++ program I've written) and am just trying to understand how the return value of .Next()
could be as expected and evaluated but not captured in the c
variable.我是 C++的新手(这是我编写的第一个 C++ 程序),我只是想了解 .Next
.Next()
的返回值如何按预期进行评估但未在c
变量中捕获。
The <=
operator has a higher precedence than the =
operator. <=
运算符的 优先级高于=
运算符。
So, with所以,与
while (int c = counter.Next() <= 5)
The compiler interprets it as:编译器将其解释为:
while (int c = (counter.Next() <= 5))
which assigns the result of the logical expression to c
, which will be 1 while the expression holds true.它将逻辑表达式的结果分配给
c
,当表达式成立时它将为 1。
Try this instead:试试这个:
int c;
while ((c = counter.Next()) <= 5)
You can add a conversion operator for Counter
, and remove the need to declare an extra variable.您可以为
Counter
添加一个转换运算符,并且无需声明额外的变量。
class Counter {
int val_;
public:
Counter() : val_(0) {}
int Next() { return ++val_; }
operator int () const { return val_; }
};
//...
Counter counter;
while (counter.Next() <= 5) {
cout << counter << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.