The namespace namespace and define pretreatment

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

In the c++ language is the namespace namespace is defined, or is the definition of scope, division scope is most common in c++ is to use {}, and the define keyword in C++, used to define a macro, or is the pretreatment variables, then the pretreatment variables and namespace and how to divide? The sample code is as follows:

#include <iostream>
using std::endl;
using std::cout;
namespace test1
{
	#define MYSIZE 1000
	const int size = 10000;
	int a = 10;
};
namespace test2
{
	#define MYSIZE 2000
	const int size = 20000;
	int a = 20;

}
int a = 40;
int main()
{
	int a = 30;
	cout<<"test1::MYSIZE="<<MYSIZE<<endl;

	cout<<"test2::MYSIZE="<<MYSIZE<<endl;
	cout<<"test1::size="<<test1::size<<endl;

	cout<<"test2::size="<<test2::size<<endl;
	cout<<"test1::a="<<test1::a<<endl;

	cout<<"test2::a="<<test2::a<<endl;
	cout<<"main::a="<<a<<endl;
	cout<<"global::a="<<::a<<endl;
	return 0;
}

The sample in addition to show the difference between namespace and define, but also with the scope of the namespace, the first is the code cannot be written like this:

cout<<"test1::MYSIZE="<<test1::MYSIZE<<endl;

cout<<"test2::MYSIZE="<<test2::MYSIZE<<endl;

A compiler error.:

namespacedefine.cpp:20:33: error: expected unqualified-id before numeric constant

namespacedefine.cpp:20:33: error: expected ';' before numeric constant

namespacedefine.cpp:21:33: error: expected unqualified-id before numeric constant

namespacedefine.cpp:21:33: error: expected ';' before numeric constant

Then use the example code, compile time warning:

namespacedefine.cpp:12:0: warning: "MYSIZE" redefined [enabled by default]

namespacedefine.cpp:6:0: note: this is the location of the previous definition

Perhaps that is repeated variables defined, said MYSIZE duplicate definition, then have a look the output results: sdoning@ubuntu:~/practice$ ./a.out

test1::MYSIZE=2000

test2::MYSIZE=2000

test1::size=10000

test2::size=20000

test1::a=10

test2::a=20

main::a=30

global::a=40

MYSIZE is taken out of the new value, also said that the concept of pretreatment statement has no namespace, whether you defined in the namespace in which programs are visible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Frederick at November 14, 2013 - 7:15 AM