如何在C++中正确地向下转换

Aha*_*ron 0 c++ memory inheritance casting private-constructor

出于任何原因,我有一个静态方法创建的对象,它调用私有构造函数.(它不是单身人士)

我想创建一个新对象派生自第一个,它有更多的成员和函数.
但这是有问题的,因为静态方法返回一个firstObject*对象,因此使用向下转换的创建secondObject*会使内存溢出.

我该怎么办?我可以访问第一个对象的代码,但是无法更改其构造函数(如果我更改它,我将不得不更改一个巨大的编写代码).

编辑:

感谢所有响应者.我可以更改要保护的构造函数.

ere*_*eOn 5

确保您的构造函数至少protected使子类可以使用它.

不确定你对内存溢出的担心但是这个:

class Base {
public:
  static Base* getInstance();
  virtual ~Base() {};
protected:
  Base() {};
};

class Derived : public Base {};

// Implementation
Base* Base::getInstance() { return new Derived(); }

int main() {
Base::getInstance();
};
Run Code Online (Sandbox Code Playgroud)

作品完美.

现在我建议你不要在那种情况下返回一个原始指针(std::unique_ptr会更好),但这可能是偏离主题的.