Overriding static variables when subclassing

后端 未结 8 408
南旧
南旧 2020-11-30 11:20

I have a class, lets call it A, and within that class definition I have the following:

static QPainterPath *path;

Which is to say, I\'m dec

相关标签:
8条回答
  • 2020-11-30 11:57

    I know this question has been answered, but there is an other way to set the value of a similar static variable for multiple classes through a helper class and some template specialization.

    It doesn't exactly answer the question since it is not connected with subclassing in any way, but I've encountered the same issue and I found a different solution I wanted to share.

    Example :

    template <typename T>
    struct Helper {
      static QPainterPath* path;
      static void routine();
    }
    
    // Define default values
    template <typename T> QPainterPath* Helper<T>::path = some_default_value;
    template <typename T> void Helper<T>::routine { do_somehing(); }
    
    class Derived {};
    
    // Define specialized values for Derived
    QPainterPath* Helper<Dervied>::path = some_other_value;
    void Helper<Dervied>::routine { do_somehing_else(); }
    
    int main(int argc, char** argv) {
      QPainterPath* path = Helper<Derived>::path;
      Helper<Derived>::routine();
      return 0;
    }
    

    Pros:

    • clean, compile time initialization
    • static access (no instantiation)
    • you can declare specialized static functions too

    Cons:

    • no virtualization, you need the exact type to retrieve the information
    0 讨论(0)
  • 2020-11-30 11:58

    I haven't tested this, but introducing a virtual function:

    struct Base {
    
        void paint() {
             APath * p = getPath();
             // do something with p
        }
    
        virtual APath * getPath() {
             return myPath;
        }
    
        static APath * myPath;
    };
    
    struct Derived : public Base  {
    
        APath * getPath() {
             return myPath;
        }
        static APath * myPath;
    };
    

    may be what you want. Note you still have to define the two statics somewhere:

    APath * Base::myPath = 0;
    APath * Derived::myPath = 0;
    
    0 讨论(0)
提交回复
热议问题