如何通过用特定参数调用基类构造函数来构建某个派生的类
因此,我想知道是否可以通过用特定参数构造基类来创建某个派生类。例如:
说;
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论