Question

I am new to c++ and undergoing a problem that i have a situation like this: I have class Huffman like this:

class HuffmanTree 
{
    public: int size,length;
    Huffman(char * argv) ; // please see it's definition below, in it's defintion i read the frequency from a file (Input.txt) which taken as sole argument (which conatains some alphabets like "aaabbaacccab" to calculate frequency).
~HuffmanTree () {};

struct Node 
{
    int value, Front, Rear;
    short flag;
    unsigned char symbol;
    int left, right;
};

Node * tree;
Node data[1000];
};
n = sym.size() - 1;

//here is the main function 
int main(int argc, char *
* argv) 

{
    int freq[256] = { 0 };
     HuffmanTree Object1(argv[1]);
     cout<<"check"<<storesym.size()<<endl;
     Object1.read( &Object1.tree, sym.size() - 1, Object1.data, Object1);
     return (0);
}

Please don't go deep in the code because my question is very simple and is this: ** In my constructor i have variable and arrays like "data[]","storesym" which i want to use in main function but their scope is limited to just Constructor definition. **Is their any way to make the scope of "data[]" which of node type and "storesym" in main function as well?

Était-ce utile?

La solution

A few different approaches :

  • Store them as data members in the class, accessible via the object (e.g. like data_size in your example - or better style is for data member to be private with public getter/setter methods)
  • Create them outside the constructor and pass them in as references
  • Create them as global variables (accessible from main and the class, but considered bad style)

Probably the simplest way is to add them to your class (same as data_size) Whatever data types you need, first add them to the class definition :

class Huffman 
{
    public: 
        int data_size;
        boolean my_flag;
        int my_value;
        Node my_array[20];
}

then assign the correct values to them in the constructor

Huffman::Huffman(char *  argv)
{
    //e.g.
    my_flag = true;
}

then read / write them from Main via the object :

int main(int argc, char * * argv) 
{
    //...
    if(Object1.my_flag)
    {
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top