Something about an unnamed C ++ namespace

#include <iostream>

namespace
{
        int a=1;
}

int a=2,b=3;

int main(void)
{
        std::cout<<::a<<::b;
        return 0;
}

I agree with my g ++, but conclusion 23, who can explain this? is this a way to access <unnamed> namespace ::a?

+3
source share
4 answers

::in ::arefers to the global namespace. An anonymous namespace should be accessible through only a(or, to be more specific, you should not do this at all)

+3
source

No, you can’t. You can get around it this way:

namespace
{
    namespace xxx
    {
        int a = 1;
    }
}
...
std::cout << xxx::a << ::b;
+3
source

You can access the global namespace, but do not redefine it.

#include <iostream>

namespace
{
        int a=1;
}


int b=3;

int main(void)
{
        std::cout<<::a<<::b;
    return 0;
}

here the output is 13.

0
source

Source: https://habr.com/ru/post/1740896/


All Articles