【问题标题】:C++ Ternary operator with scope resolution and condition具有范围解析和条件的 C++ 三元运算符
【发布时间】:2017-09-14 06:15:51
【问题描述】:

以下代码未由特定编译器编译。

#include <iostream>

using namespace std;

class A{
        public:
                static const int x = 12;
                static const int y = 16;
};

int main(){
        int a = 12, b = 19;
        int z = (a==b)?(A::x):(A::y);
        cout<<z<<endl;
        return 0;
}

编译器g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-11) 编译成功。

编译器 g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-17) 导致编译错误

test.cpp:(.text+0x20): undefined reference to `A::x'
test.cpp:(.text+0x28): undefined reference to `A::y'

如果我将int z = (a==b)?(A::x):(A::y); 行中的条件(a==b) 替换为truefalse,则编译成功。

是什么原因以及如何为指定的编译器修复它?

【问题讨论】:

  • 您似乎发现了一个已修复的编译器错误。
  • 后面的编译器可能能够将其全部优化为z = 16。看看生成的机器码看看。
  • 你在打开 C++0x/11 的情况下编译了吗?无法重现here

标签: c++ linux g++ ternary-operator


【解决方案1】:

看起来像 gcc 4.4 的弱/错误 C++0x 符号链接实现。 似乎 gcc 4.4 告诉链接器有符号,但它忘记在其中一个编译单元中“实现”它们。

我猜如果您将静态成员 A::x 和 A::y 的初始化显式放入一个唯一的编译单元(例如相应的 .cpp 文件),那么您的代码可能与两种编译器都兼容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-28
    • 2010-09-09
    • 2016-12-12
    • 1970-01-01
    • 2012-04-20
    • 2016-08-15
    • 2011-05-19
    相关资源
    最近更新 更多