What does "::" mean in C ++?

8

I have doubts about using the colon :: , used to do class implementation, [tipo] [classe]::[método] . It is also used, for example, in std::cout . What exactly would these two double points be and what do they serve for?

    
asked by anonymous 18.09.2015 / 04:19

1 answer

9

This is the scope resolution operator . He gives context to what he is referring to, he disambiguates a possible situation where there may be confusion between two or more members. It is used in two situations.

  • To indicate that a member belongs to a certain namespace as in the example of std::cout . std is namespace . It's a different family of components, so to use members of a family other than the current one you can not just use the member's name, you have to use his last name as well.

  • Indicate to which class a member belongs. This is necessary when you are going to define the methods (not when you are going to declare). Without telling which class it belongs the compiler has no way of knowing what it is implementing and this is a fundamental information.

It is also used to access members that belong globally to the class and not to the instance, ie to access static members.

Well, there is a way to not need the fully qualified name, but that's another matter.

So you've essentially learned everything you needed about it.

Simplified example:

namespace exemplo {
    public class classe {
        static int membro = 0;
        int metodo(); //declarou o método dentro da classe
    }
}
int classe::metodo() { //definiu o método já declarado que pertence a "classe"
    return 0;
}

auto x = new exemplo::classe(); //instanciando "classe" que faz parte do "exemplo"
std::cout << x.metodo(); //estou chamando pela instância
std::cout << exemplo::classe::membro; //estou chamando um membro da classe

Both will print 0.

    
18.09.2015 / 04:34