【发布时间】:2011-07-23 16:37:13
【问题描述】:
这是交易。我有一个静态类,其中包含几个用于获取输入的静态函数。该类包含一个私有静态成员变量,用于指示用户是否输入了任何信息。每种输入法都会检查用户是否输入了任何信息,并相应地设置状态变量。我认为这将是使用三元运算符的好时机。不幸的是,我不能,因为编译器不喜欢那样。
我复制了这个问题,然后尽可能地简化了我的代码以使其易于理解。这不是我的原始代码。
这是我的头文件:
#include <iostream>
using namespace std;
class Test {
public:
void go ();
private:
static const int GOOD = 0;
static const int BAD = 1;
};
这是我使用三元运算符的实现:
#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;
}
当我尝试编译它时,我收到以下错误消息:
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。)
【问题讨论】:
标签: c++ static ternary-operator static-members