[英]composition and inheritance - abstract class
Lets suppose i have a super class WorkStation
, and two subclass StationNormal
, StationAdvanced
. 让我们假设我有一个超级
WorkStation
,以及两个子类StationNormal
, StationAdvanced
。 I have another class Robot
, which has a WorkStation
pointer that will start as a StationAdvanced
but it can change, but my class WorkStation
is a abstract class. 我有另一个类
Robot
,它有一个WorkStation
指针,它将作为StationAdvanced
启动,但它可以改变,但我的类WorkStation
是一个抽象类。 I think class Robot
should be something like this: 我认为类
Robot
应该是这样的:
class Robot{
private:
WorkStation * actualStation;
...
}
My question is how Robot class constructor should be defined if my class WorkStation
is abstract. 我的问题是如果我的类
WorkStation
是抽象的,应该如何定义Robot类构造函数。
You need to let StationNormal
and StationAdvanced
inherit WorkStation
An example would be: 你需要让
StationNormal
和StationAdvanced
继承WorkStation
一个例子是:
class StationNormal:public WorkStation
{
....
}
public Robot(WorkStation* workStation)
{
actualStation = workStation;
}
In main method for example: 在主要方法中,例如:
new Robot(new StationNormal()) ;
I think the following should be sufficient: 我认为以下内容应该足够了:
class Robot{
private:
WorkStation * actualStation;
public:
Robot();
Robot(WorkStation * w);
}
Robot::Robot() // constructor that takes no arguments
{
actualStation = new StationAdvanced();
}
Robot::Robot(WorkStation * w) // constructor that takes specific WorkStation
{
actualStation = w;
}
You can invoke it with: 您可以使用以下命令调用它:
Robot rob1(),
rob2(new StationAdvanced()),
rob3(new StationNormal());
Well, in your constructor you would instantiate the actual WorkStation and tell the pointer ( WorkStation * actualStation
) to point to it. 好吧,在构造函数中,您将实例化实际的WorkStation并告诉指针(
WorkStation * actualStation
)指向它。 Put this in your constructor: 把它放在你的构造函数中:
this->actualStation = new StationAdvanced(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.