Overriding static variables when subclassing

后端 未结 8 468
南旧
南旧 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:41

    You might be able to do a variant on a mix in or Curiously recurring template pattern

    #include 
    
    typedef const char QPainterPath;
    
    class Base
    {
    public:
        virtual void paint() { printf( "test: %s\n", getPath() ); }
        virtual QPainterPath* getPath() = 0;
    };
    
    template 
    class Holder : public Base
    {
    protected:
        static QPainterPath* path;
        virtual QPainterPath* getPath() { return path; }
    };
    
    class Data1 : public Holder
    {
    };
    
    class Data2 : public Holder
    {
    };
    
    template <> QPainterPath* Holder::path = "Data1";
    template <> QPainterPath* Holder::path = "Data2";
    
    int main( int argc, char* argv[] )
    {
    Base* data = new Data1;
    data->paint();
    delete data;
    
    data = new Data2;
    data->paint();
    delete data;
    }
    

    I have just run this code in CodeBlocks and got the following:

    test: Data1
    test: Data2
    
    Process returned 0 (0x0)   execution time : 0.029 s
    Press any key to continue.
    

提交回复
热议问题