PDA

View Full Version : sharing struct data throughout program



vonCZ
6th July 2007, 12:59
I have a struct as a private member of my main Window class, like so:


class Window : public QWidget
{
Q_OBJECT
public:
//etc

private:
//etc
struct Comp {

short dataNUM_TOTc;
char *lyBuName[24];
bool onMA[24];
short dataTYPE[24];
} comp[7];

The values of the instances of the struct, comp[0-6], are initialized through a member function of the Window class and determine how my QWidgets are set up. I would like to be able to access (read) the values of this struct in the constructor function of another class, defined in another .cpp file. How to do this?

edit: Actually, I've no reason to make it private, so assume it's public instead of private.

vonCZ
6th July 2007, 18:55
strange: when I add "curCOMP" and "preCOMP" to the struct:


struct Comp {


short curCOMP; // here
short preCOMP; // and here


short dataNUM_TOTc;
char *lyBuName[24];
bool onMA[24];
short dataTYPE[24];

//alt

} comp[7]; the program crashes. If I change preCOMP from short to int--or if I move both lines below dataTYPE[24] to //alt--it doesn't crash.

What's going on??

jpn
7th July 2007, 08:16
I would like to be able to access (read) the values of this struct in the constructor function of another class, defined in another .cpp file. How to do this?

edit: Actually, I've no reason to make it private, so assume it's public instead of private.
It would be suggested to provide public accessor functions to private data instead of making data itself public. I don't know what's your case but perhaps you could also make accessors and data static (provided that there is always a single Window). This way you wouldn't need a pointer/object to access data.

vonCZ
9th July 2007, 17:21
thanx JPN. Here's what i did based on your advice and looking around a bit on the web: first, I removed the "Comp" struct from the "Window" constructor function (above) and have created a new class in separate files:

dafo.h

#ifndef DAFO_H
#define DAFO_H

class Dafo
{

private:
static short dataNUM_TOTc;
//other variables.......

public:
Dafo();
~Dafo();

//GETs
static short get_dataNUM_TOTc() { return dataNUM_TOTc; }

//SETs
static void set_dataNUM_TOTc(short value) { dataNUM_TOTc = value; }

};

#endif

I initialize the private variables in dafo.cpp like so:

#include "dafo.h"

short Dafo::dataNUM_TOTc = 7;
// other variables

Dafo::Dafo(void){
}

Dafo::~Dafo(){

// delete this;

}

...and that's it. Now I can access get/set member functions of Dafo from any class-file which includes: #include "dafo.h"

Anyway, pretty basic C++ I guess, but I thought I would post this in case I've made some obvious C++ programming/protocol mistakes that someone might point out.

thanks again