c++ - 如何使用 UML 类图实现从父类派生的类对象类型
问题描述
我通过使用类创建简单的交通灯逻辑来学习 C++。我在其中找到了这个 UML 图,我想基于它创建对象类型。但是,我创建了 TrafficLight 类对象,难以理解控制类逻辑部分。
编辑
对我来说,我只想为 N、W、S 和 E 创建交通灯。我可以单独设置灯光。也许我想偏离UML。我只是想学习一种有效的方法来做到这一点,任何帮助表示赞赏。我看到 UML 操作与构造函数重叠。
这是我在 C++ 中实现的 UML 图像
我不明白控制对象部分。我的理解是控制与 TrafficLight 类直接相关。
添加了详细的对象图
这里我需要使用接口名称 N、W、E、S 进行类控制还是只需要四个类实例就足够了?
从这个 UML 如何实现具有四个对象 N、W、E、S 的控件类?
这是我的代码,使用 -std=c++11 编译器标志。
#include <iostream>
using namespace std;
class TrafficLight {
public:
enum light { red, amber, green};
// Setting the light by default red
TrafficLight(light=red){
cout << "constructed" << '\n';
} // Default constructor
// light state() {
// std::cout << "Setting the t light" << '\n';
// }
void CreateLight(light l) {
std::cout << "Creating lights" << '\n';
// show on console which lights are turned on.
if (l == light::green)
cout << "Green ligh is ON" << '\n';
else if (l == light::amber)
cout << "Amber ligh is ON" << '\n';
else
cout << "Red ligh is ON" << '\n';
}
void SwitchLight(light l) {
// switchLight operations executed
}
private:
light _state;
};
// Wondering how to proceed here? Create Light control for west, east, north and south.
class Control : public TrafficLight {
};
int main(void) {
/* code */
std::cout << " Welcome to Trafficlight signaling system " << '\n';
TrafficLight x(TrafficLight::green);
TrafficLight::light l;
// l = x.state();
l = TrafficLight::green;
x.CreateLight(TrafficLight::green);
x.CreateLight(TrafficLight::red);
x.CreateLight(TrafficLight::amber);
x.CreateLight(TrafficLight::green);
// run the derived class instance to create N,S,W,E
// Control c_obj;
return 0;
}
解决方案
根据您拥有的图表,您Control
将拥有 4 个TrafficLight
.
虽然它没有说明它究竟是如何工作的,但我认为意图是从and调用switchLight
and ,您不需要直接使用and 。createLight
switchControl
createLights
switchLight
createLight
一些代码看起来有点像:
class TrafficLight
{
public:
enum lightColor {red, amber, green};
TrafficLight(lightColor color) : color(color){}
void SwitchLight()
{
// Change to the next state.
if(color == green) color = red;
else ++color;
}
private:
lightColor color;
}
class Control
{
public:
Control() : N(green), W(red), S(green), E(red){}
void SwitchControl()
{
// All lights change to the next state.
N.SwitchLight();
W.SwitchLight();
E.SwitchLight();
S.SwitchLight();
}
private:
TrafficLight N, W, S, E;
}
int main()
{
Control c; // N and S are green, W and E are red.
c.SwitchControl(); // N and S are red, W and E are amber.
c.SwitchControl(); // N and S are amber, W and E are green.
}
您要调用的唯一函数是Control
, 和的构造函数SwitchControl()
。
请注意,我没有调用lightColor
s 的全名,您实际上需要这样做才能使代码正常工作。我还删除了Create
函数,因为它们与 ctor 有点重叠。
推荐阅读
- mysql - 如何修复列的数据过长
- jquery - 未捕获的类型错误:无法读取未定义的属性
- angular - 在打字稿中将数据从一个值对象复制到另一个:类型错误:无法读取未定义的属性(读取子字符串)“
- reactjs - NextJS getStaticProps 没有被调用
- go - 获取资源 SKU 以在 GCP 中查找资源价格 (go)
- sql - SQL如何同步聚合表
- python - 获取合并两个数据集的数据集格式
- python - 不确定这里出了什么问题,无论我尝试什么,它都会返回 TypeError: 'NoneType' object is not iterable
- oracle - 数字的 Oracle 字节大小
- r - 在 R Lubridate 中解析我的日期时间时出现问题