为什么静态成员变量与三元运算符不匹配? [英] Why don't static member variables play well with the ternary operator?
问题描述
这是协议。我有一个静态类,它包含用于获取输入的几个静态函数。该类包含一个私有静态成员变量,用于指示用户是否输入了任何信息。每个输入法检查用户是否输入任何信息,并相应地设置状态变量。我认为这将是一个好时机使用三元运算符。不幸的是,我不能,因为编译器不喜欢这样。
Here's the deal. I have a static class which contains several static functions used for getting input. The class contains a private static member variable for indicating whether the user entered any information. Each input method checks to see whether the user entered any information, and sets the status variable accordingly. I think this would be a good time to use the ternary operator. Unfortunately, I can't, because the compiler doesn't like that.
我复制了这个问题,然后简化我的代码尽可能多,理解。这不是我的原始代码。
I replicated the problem, then simplified my code as much as was possible to make it easy to understand. This is not my original code.
这是我的头文件:
#include <iostream>
using namespace std;
class Test {
public:
void go ();
private:
static const int GOOD = 0;
static const int BAD = 1;
};
这是我的三元运算符的实现:
Here's my implementation with the ternary operator:
#include "test.h"
void Test::go () {
int num = 3;
int localStatus;
localStatus = (num > 2) ? GOOD : BAD;
}
这里是主要功能:
#include <iostream>
#include "test.h"
using namespace std;
int main () {
Test test = Test();
test.go();
return 0;
}
当我试图编译这个,我得到这个错误信息:
When I try to compile this, I get this error message:
test.o: In function `Test::go()':
test.cpp:(.text+0x17): undefined reference to `Test::GOOD'
test.cpp:(.text+0x1f): undefined reference to `Test::BAD'
collect2: ld returned 1 exit status
但是,如果我替换为:
localStatus = (num > 2) ? GOOD : BAD;
:
if (num > 2) {
localStatus = GOOD;
} else {
localStatus = BAD;
}
代码按预期编译和运行。什么模糊的C ++规则或GCC角的情况负责这种疯狂? (我在Ubuntu 9.10上使用GCC 4.4.1。)
The code compiles and runs as expected. What obscure C++ rule or GCC corner case is responsible for this lunacy? (I'm using GCC 4.4.1 on Ubuntu 9.10.)
推荐答案
这是根据C ++标准。三元运算符构成一个单值,在运行时引用 GOOD
或 BAD
。左值到右值转换不会立即应用于左值 GOOD
或 BAD
,因此您需要定义 GOOD
和 BAD
。
This is according to the C++ Standard. The ternary operator does constitute a single lvalue that will refer to either GOOD
or BAD
at runtime. The lvalue to rvalue conversion is not applied immediately to either the lvalue GOOD
or BAD
, and therefor you require a definition of GOOD
and BAD
.
请参阅核心语言问题报告 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#712 。
See the core language issue report http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#712 .
作为解决方法,您可以对 int
(读取其值,从而对右值转换执行左值)应用显式转换或使用读取值的运算符,例如 +
:
As a workaround, you can apply explicit casts to int
(which reads their values, thereby doing an lvalue to rvalue conversion) or use an operator that reads the value, like +
:
localStatus = (num > 2) ? +GOOD : +BAD;
这篇关于为什么静态成员变量与三元运算符不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!