Global namespace in C + +

Source: Internet
Author: User
Tags include

We should know that the traditional C + + has only one global namespace, but because of the growing size of the current program, the division of the program is becoming more and more thin, global scope becomes more and more crowded, everyone may use the same name to implement different libraries, As a result, programmers may have conflicting names when merging programs. namespace introduces complexity and solves the problem. namespace allows like classes, objects, and functions to be clustered under a name. Essentially, namespace is a subdivision of the global scope. I think we've all seen a procedure like this:

hello_world.c
#include <iostream>
using namespace std;
  int main()
{
  printf("hello world !");
  return 0;
}

I think a lot of people know so much about namespace, but namespace is far more than that, let's learn more about namespace

The basic format of the namespace format isnamespace identifier
{
  entities;
}
举个例子,
namespace exp
{
  int a,b;
}

It's kind of like a class, but it's completely two different types.

In order to use the variables in namespace outside the namespace we use:: operator, as follows

Exp::a

Exp::b

Using namespace can be an effective way to avoid redefining problems

#include <iostream>
using namespace std;
  namespace first
{
 int var = 5;
}
  namespace second
{
 double var = 3.1416;
}
  int main () {
 cout << first::var << endl;
 cout << second::var << endl;
 return 0;
}

The result is

5

3.1416

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.