使用Base类静态const变量来构造基类,我可以这样做吗?

时间:2012-04-07 16:47:39

标签: c++ inheritance static constructor const

我有一个基础和派生类。基类构造函数有一些静态const变量。可以在派生类构造函数中使用它来构造基类变量??

示例代码将是

  //Base.hpp    
  class Base {
   public:
        Base(int value_, long sizee_);
   private:
        int value;
        int sizee;
   protected:
        static const int ONE = 1;
        static const int TWO = 2;
        static const long INT_SIZE = (long)sizeof(int);
        static const long LONG_SIZE = (long)sizeof(long);
  };

  //Base.cpp
  Base::Base(int value_,int sizee_):value(value_),sizee(sizee_) {
  }

  //Derived.hpp
  class Derived: class Base {
    public:
          Derived();
  };

  //Derived.cpp
  Derived::Derived():Base(ONE+TWO,INT_SIZE+LONG_SIZE) {
  }

这里有ONE,TWO,INT_SIZE,LONG_SIZE是基类静态变量,我将用它来构造基类本身。这种做法好吗?请指教。

1 个答案:

答案 0 :(得分:1)

是的,没关系。当您创建Dervide对象时,将初始化所有static个成员。也就是说,除非您有static Derived个对象。