How do I use namespaces and classes?

Sorry if this is a stupid question, but I'm learning C ++ (I usually code in C) and I don't understand how to use namespaces and classes. Should they be declared in header files? How do I declare functions in a namespace? And let me tell you that I am working on a large project with different files. And I define a namespace in a file, but then I want to add more functions to that same namespace, but these functions are defined in a different file. It can be done? For example:

file1.cpp

namespace Example {
   int vartest;
   void foo();
}

      

file2.cpp

int othervar;
void otherfoo(); // How can I add this and othervar to the Example namespace?

      

Thank!

+3


source to share


1 answer


Just declare it equivalent to 1 ofnamespace

the same "name"!

file1.cpp

namespace Example {
   int vartest;
   void foo();
}

      

file2.cpp

namespace Example {
    int othervar;
    void otherfoo();
}

      

Namespaces are concatenated.

Should they be declared in header files?

Not. You can declare anyone namespace

inside namespace

. (Note that the "global scope" is also namespace

)

How do I declare functions in a namespace?

Just declare it in namespace

. How did you do that.



And let me tell you that I am working on a large project with different files. And I define a namespace in a file, but then I want to add more functions to the same namespace, but these functions are defined in a different file. It can be done?

Namespaces with the same name in the same namespace are combined.

namespace X { void foo(){} }
namespace X { void foo(){} }  //Error, redefinition of `foo` because the namespace ::X is merged

      


namespace X { void foo(){} }
namespace Y { void foo(){} }  //Ok. Different name spaces... 

      


namespace X { void foo(){} }  // ::X
namespace Y { void foo(){} }  // ::Y

namespace Y {
   namespace X {  // namespace ::Y::X here isn't same as ::X
     void foo(){}  //OK
   }
}

      


1 recall that the so-called global scope is a namespace known asglobal namespace

+4


source







All Articles