初始化派生类的成员(C++)

Han*_*ank -1 c++ constructor derived-class initializing

初始化从其基类中转换的派生类的首选方法是什么?

请考虑以下情形:

    class A{
        public:
           A();
           ~A();
    }

    class B : public A{
        public:
           B() {m_b = 0.0;};
           ~B();
           float GetValue(){return m_b;};

        private: 
           float m_b;
    }


    A* a = new A;
    B* b = static_cast<B*>(a);

    float val = b->GetValue();   // This was never initialized because it was not constructed
Run Code Online (Sandbox Code Playgroud)

我目前的解决方案是手动调用Initialize()函数,该函数将像构造函数那样执行必要的初始化.

虽然看起来很草率,但必须有一个更好/更清洁的方法.

非常感谢任何帮助和指导!

Ton*_*ion 5

这是一个错误的结构:

A* a = new A;
B* b = static_cast<B*>(a);
Run Code Online (Sandbox Code Playgroud)

编辑

它应该是:

B* b = new B();
Run Code Online (Sandbox Code Playgroud)

因为,正如sbi指出的那样,A没有一个名为GetValue()的虚函数,因此永远无法从A调用它.

不要从A*到B*执行static_cast.

  • @Matt:问题**在投射中是**,因为你展示的投射会调用[未定义的行为](http://en.wikipedia.org/wiki/Undefined_behavior). (2认同)