Untitled namespace vs private variables

I read other questions here, and there is something that bothers me and hopefully this can be explained. I am sure it is simple, but it alludes to me.

So, in C ++, we have private variables that are only viewable in the class:

class MyClass
{
    private:
        int i;
};

But we can also have unnamed namespaces:

namespace
{
    int i;
}

Both seem private to the class, but in the second case, you cannot see that they exist from the header file. From reading other questions, it seems that the functions are different since you cannot pass class objects to them? But I'm not sure what the difference is here for variables.

Is there a flaw for the second method, which means that you should still use private variables?

+5
source share
4

.

Integer i MyClass.

i MyClass .

private i static:

//.h
class MyClass
{
    private:
        static int i;
};

i :

//.cpp
int MyClass::i = 0;
+13

...

, . -; .

; , . , , , , . , (.. ), ; , .

, , ?

, , .

, . , . , , - , , .

+5

/. , , .

+3

These are completely different concepts. The private data member is displayed only for the class, and in a non-static case, each instance of the class has one of them. An anonymous namespace allows you to make the code available only for other code in the same file. Therefore, in the case of a single variable, intall code defined in the same place as the anonymous namespace will see the same single variable.

+3
source

All Articles