Two ways using global objects in C++

1.Through include

Globe.h

#ifndef GLOBE_H_
#define GLOBE_H_

int g = 0;

#endif /* GLOBE_H_ */

A.h

#ifndef A_H_
#define A_H_

#include "Globe.h"  // through include

class A {
public:
	A() { g = 1; }
	virtual ~A() {}  // must be implemented
};

#endif /* A_H_ */
main.cc

#include "A.h"
#include <iostream>
using namespace std;

int main ()
{
	cout<<g<<endl;  // 0
	A a;
	cout<<g<<endl;  // 1
	return 0;
}

In this example, we use include method to use global objects. Because Globe.h is included in A.h, in main.cc we do not need to include Globe.h again.

2.Through extern

Globe.h is same with above.

A.h

#ifndef A_H_
#define A_H_

extern int g;  // through extern

class A {
public:
	A() { g = 1; }
	virtual ~A() {}  // must be implemented
};

#endif /* A_H_ */

main.cc

#include "Globe.h"  // must have
#include "A.h"
#include <iostream>
using namespace std;

int main ()
{
	cout<<g<<endl;  // 0
	A a;
	cout<<g<<endl;  // 1
	return 0;
}

In this example, we use extern method to use global objects. Note that in main.cc we have to include Globe.h so that extern can work well, while in A.h Globe.h is not included.

To sum up, using extern is better than using include for the latter will also include several useless code in terms of global object.



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章