C++ Object-Oriented Programming (5)-Advanced Namespace

namespace means "namespace", also known as "namespace" or "namespace"

By using Namespaces, we can organize a group of classes, objects or functions that are globally valid under
one name. In other words, it divides the global scope into many subdomains. Each subdomain is called
a namespace, which divides the global members into many subdomains.


The format of using
namespace is: namespace identifier
{

namespace-body
}
where identifier is a valid identifier, and namespace-body is a set of classes, objects
and functions contained in the namespace . For example:
namespace general
{
int a, b;
}

In this example, a and b are integer variables in the general namespace. To access
these two variables outside of this namespace , we must use the range operator ::. For example, to access the previous two variables, we need
to write:
general :: a

The role of
general::b namespaces is that global objects or functions are likely to have the same name and cause repeated definition errors. The use of namespaces can avoid these errors . E.g:


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

}

result:
5
3.1416

In this example, two global variables called var exist at the same time, one is defined under the name space first, and the other is defined
under second. Because we use the name space, there will be no duplicate definition errors.

Using namespaces (using namespace)
later use using directive with a current nested namespace with a specified name space may be attached to a
play, so that the objects and functions defined in this namespace can be accessed as if they It is
defined in the global scope . Its use follows the following prototype definition:
using namespace identifier;

//using namespace example
#include <iostream.h>
namespace first {
int var = 5;
}
namespace second {
double var = 3.1416;
}
int main () {
using namespace second;
cout << var << endl;
cout << (var*2) << endl;
return 0;
}

result:

  3.1416

6.2832

在这个例子中的 main函数中可以看到,我们能够直接使用变量 var 而不用在前面加任
何范围操作符。
这里要注意,语句 using namespace 只在其被声明的语句块内有效(一个语句块指在一对花括号{}内的一组指令),如果 using namespace是在全局范围内被声明的,则在所有代码中都有效。



别名定义(alias definition)
我们以可以为已经存在的名空间定义别名,格式为:
namespace new_name = current_name ;


Guess you like

Origin blog.csdn.net/hgz_gs/article/details/51841882