如何通过用特定参数调用基类构造函数来构建某个派生的类

发布于 2025-01-26 08:52:08 字数 652 浏览 2 评论 0原文

因此,我想知道是否可以通过用特定参数构造基类来创建某个派生类。例如:

说;

class Base
{
    Base::Base(char derived_selector){...};
}
class DerivedA: public Base
{
   char id_;
   DerivedA::DerivedA(char id):id_(id){};
}

class DerivedB: public Base
{
   int id_;
   DerivedB::DerivedB(int id):id_(id){};
}

现在,从基地继承的原因尚不清楚,但是由于它的一个例子,我认为理解这里的房地产应该很好。

我要实现的是,当我称

Base *ptrA  = new Base('A');
Base *ptrB  = new Base('B');

构造函数为我提供派生类的选择并为PTRA构造一个派生对象,而PTRB的派生对象。

我确实认为可能存在一些问题,例如基本构造师如何知道如何设置派生类的属性,但我觉得可以以某种方式实现它。另外,如果确实有可能,这是一种以对象为导向的好方法,或者应该决定在我要构建一个派生类的时候,我用简单的语言来决定哪一个?

So I want to know if its possible to create a certain derived class by constructing the base class with a certain argument. For example:

lets say;

class Base
{
    Base::Base(char derived_selector){...};
}
class DerivedA: public Base
{
   char id_;
   DerivedA::DerivedA(char id):id_(id){};
}

class DerivedB: public Base
{
   int id_;
   DerivedB::DerivedB(int id):id_(id){};
}

Now the reason for inheritance from base here is not clear but since its an example I think it should be fine to understand the realtionship here.

What I want to achieve is when I call

Base *ptrA  = new Base('A');
Base *ptrB  = new Base('B');

The constructor makes the selection of the derived class for me and constructs a DerivedA object for ptrA, and a DerivedB object for ptrB.

I do think there could be some problems like how would the Base constructor know how to set the attributes of the derived class but I feel like it could be achieved somehow. Also if it is indeed possible would this be a good object oriented way or should just decide which one I am making with a simple if else statement when I am going to construct a derived class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文