0

How can I make it a global arrays of objects, like QPoint point[5][6];

global.h

#include <QPoint>
extern QPoint point[5][6];//Am I correct?

global.cpp

#include <global.h> // How to initialize???

main.cpp

#include <global.h>
use them;
Zhang LongQI
  • 494
  • 1
  • 11
  • 25
  • 4
    I'd strongly recommend not to do this. The whole structure of the Qt libraries is object oriented; throwing globals in there makes the code hard to read and maintain, and error prone. Define the `QPoint` in the structure that needs it, and consider using `std::vector` or one of the Qt given containers instead of C style arrays – nikolas Aug 29 '13 at 14:15
  • It's really hard to turn my mind from procedure-oriented mind.Do you have some good books or websites about object oriented mind and how to design good classes recommend to me . – Zhang LongQI Aug 30 '13 at 11:59
  • 1
    http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list has some great book recommendations and for general design patterns [GoF](http://en.wikipedia.org/wiki/Design_Patterns) is a good read, but that's not C++ specific – nikolas Aug 30 '13 at 12:08

1 Answers1

3

Globals are evil. Alas, the idiomatic way to do it is:

  1. Declare the global variable extern in a header file.
  2. Define the variable in one source file (and no more). Include the declaration from the header to ensure the definition is correct.
  3. Use the variable in any number of source files; include the declaration from the header.

global.h

#ifndef BENHUAN_GLOBAL_H_INCLUDED
#define BENHUAN_GLOBAL_H_INCLUDED
#include <QPoint>
extern QPoint point[5][6]; // declaration
#endif

global.cpp

#include "global.h'
QPoint point[5][6]; // definition

main.cpp

#include "global.h"

...
   point[1][2] = QPoint(5,6);
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313