首页 > 解决方案 > 如何使用 UML 类图实现从父类派生的类对象类型

问题描述

我通过使用类创建简单的交通灯逻辑来学习 C++。我在其中找到了这个 UML 图,我想基于它创建对象类型。但是,我创建了 TrafficLight 类对象,难以理解控制类逻辑部分。


编辑

对我来说,我只想为 N、W、S 和 E 创建交通灯。我可以单独设置灯光。也许我想偏离UML。我只是想学习一种有效的方法来做到这一点,任何帮助表示赞赏。我看到 UML 操作与构造函数重叠。


这是我在 C++ 中实现的 UML 图像

在此处输入图像描述

我不明白控制对象部分。我的理解是控制与 TrafficLight 类直接相关。

添加了详细的对象图

在此处输入图像描述 其中每个UML箭头显示1.1我不知道是什么意思?

这里我需要使用接口名称 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;
}

标签: c++oopuml

解决方案


根据您拥有的图表,您Control将拥有 4 个TrafficLight.

虽然它没有说明它究竟是如何工作的,但我认为意图是从and调用switchLightand ,您不需要直接使用and 。createLightswitchControlcreateLightsswitchLightcreateLight

一些代码看起来有点像:

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()

请注意,我没有调用lightColors 的全名,您实际上需要这样做才能使代码正常工作。我还删除了Create函数,因为它们与 ctor 有点重叠。


推荐阅读