在基类构造函数中,我希望实例是派生类。我可以做这样的事情吗?
class InterfaceClass // Final user only sees this class
{
enum class TYPE
{
CHILDONE
};
public:
InterfaceClass(TYPE);
virtual void hello_world() = 0;
virtual void print_class();
};
class ChildOne : public InterfaceClass
{
public:
ChildOne() = default;
void hello_world();
private:
};
InterfaceClass::InterfaceClass(TYPE type)
{
if (type == CHILDONE)
this = new ChildOne();
else
throw "NOT HANDLED";
}
void InterfaceClass::hello_world() {
std::cout << "Hello world from InterfaceClass" << std::endl;
}
void InterfaceClass::print_class() {
std::cout << "Not implemented" << std::endl;
}
void ChildOne::hello_world() {
std::cout << "Hello world from ChildOne" << std::endl;
}
// Final user will see only declaration of InterfaceClass
int main()
{
InterfaceClass* ic = new InterfaceClass(InterfaceClass::TYPE::CHILDONE);
ic->hello_world();
}
我想构建一个像这样的架构。 但我不知道如何正确地做到这一点。
最佳答案
I would like to instantiate
A
as a child, depending on an enum given in the constructor [...]
这个
this = new ChildOne();
没有任何意义。 this
pointer is a prvalue ,您不能为其分配任何内容。从描述来看,您似乎需要一个返回派生类的工厂函数,具体取决于枚举 TYPE
.
#include <memory> // std::unique_ptr
std::unique_ptr<InterfaceClass> InterfaceClass::createInstance(TYPE type)
{
switch (type) {
case TYPE::CHILDONE:
// use smart pointer instead the raw pointers
return std::make_unique<ChildOne>();
// ... more
default:
throw "NOT HANDLED";
}
}
此外,底座 InterfaceClass
class required a virtual析构函数,以便删除通过 InterfaceClass
派生的类指针(即 std::unique_ptr<InterfaceClass>
在 createInstance
中返回),执行定义的行为。
简而言之,你可能会这样做
#include <memory>
class InterfaceClass
{
public:
enum class TYPE
{
CHILD_ONE
// .... CHILD_TWO
};
virtual ~InterfaceClass() {} // required for defined behavior!
virtual void hello_world() = 0;
virtual void print_class() = 0;
static std::unique_ptr<InterfaceClass> createInstance(TYPE type);
};
class ChildOne : public InterfaceClass
{
public:
void hello_world() override; // (Optionally) override the virtual functions
void print_class() override; // (Optionally) override the virtual functions
}
关于c++ - 如何在构造函数中将基类实例化为派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76785807/