简体   繁体   中英

Static member variable initialization

As posted below. How would i initialize the alphabet using alphabet's own member function for my static member variable? I need to do the initialization from within the "Text.cpp" implementation file.

Text.h

class Text {
private:

    struct Font {
        enum Enum {
            Arial,
            Menlo,
            Times
        };
    };

    static Alphabet alphabet[3]; // library of letters

}; // class

I need something as seen below, just the correct way of accomplish the task. I also need to initialize the alphabet only once for the duration of my runtime, thus i have made alphabet static. Thank you. ^^

Text.cpp

Alphabet Text::alphabet[Text::Font::Arial].Load("./Alphabet/", "Arial", ".xml"));
Alphabet Text::alphabet[Text::Font::Menlo].Load("./Alphabet/", "Menlo", ".xml"));
Alphabet Text::alphabet[Text::Font::Times].Load("./Alphabet/", "Times", ".xml"));

Assuming that Alphabet has a parametrized constructor, you can do it this way in a single translation unit (in Text.cpp file),

Alphabet Text::alphabet[] = { ("./Alphabet/", "Arial", ".xml"), 
                              ("./Alphabet/", "Menlo", ".xml"),
                              ("./Alphabet/", "Times", ".xml") };

Option 1: All the static variables declared in the class should be redefined in .cpp (implementation file, in your case Text.cpp), you shall initialize the variables in the definition.

Option 2: Add a new static method(function) in class "Text" to initialize the static members. Since your static data member in private section. Declare the method in public section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM