ton*_*uez 2 c++ oop inheritance constructor class
在基类构造函数中,我希望实例是派生类。我可以做这样的事情吗?
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();
}
Run Code Online (Sandbox Code Playgroud)
我想构建一个像这样的架构。但我不知道如何正确地做到这一点。
我想实例
A
化为一个孩子,具体取决于构造函数中给出的枚举[...]
这
this = new ChildOne();
Run Code Online (Sandbox Code Playgroud)
没有任何意义。该this
指针是纯右值,您不能向其分配任何内容。从描述来看,您似乎需要一个返回派生类的工厂函数,具体取决于 enum 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";
}
}
Run Code Online (Sandbox Code Playgroud)
此外,基InterfaceClass
类需要一个虚拟析构函数,以便通过InterfaceClass
类指针删除派生类(即std::unique_ptr<InterfaceClass>
return in 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
}
Run Code Online (Sandbox Code Playgroud)