简体   繁体   中英

C++ Ternary operator with scope resolution and condition

Following code is not being compiled by an specific compiler.

#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;
}

Compiler g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-11) compiled it successfully.

Compiler g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-17) is causing compilation error

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

If I replace condition (a==b) in line int z = (a==b)?(A::x):(A::y); by true or false , then it gets compiled successfully.

What is the reason and how to fix it for specified compiler?

Looks like a weak/buggy C++0x symbol-linkage implementation of gcc 4.4. Seems that gcc 4.4 tells the linker that there are symbols but it forgot to "implement" them in one of the compilation units.

I guess if you put the initialization of the static members A::x and A::y explicitly into one unique compilation unit (eg corresponding .cpp file) then your code may be compatible with both compilers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM