【发布时间】:2014-02-25 15:27:29
【问题描述】:
嗯,我真的不知道什么标题是最好的。所以,我正在尝试实现一个“布尔电路设计师”(不是家庭作业,用于学习目的)。我从一个简单的例子开始:给定一个输入端口、输出端口、2 根电线、一个电源和继电器。电路如下所示:
- 输入端口连接到第一根线
- 输出端口 iis 连接到第二根线
- 第二根线的另一端接电源
- 2根线中间接继电器
看起来像:
->in------------------------>
|
power-----------relay----------out->
它只是否定输入位。我在 C++ 中实现它,所以想要建立一个好的类层次结构。
如您所见,输入可以连接到电线,输出可以连接到电线,电线可以连接到继电器,等等。为此,我有一个空类port,这是所有电线、继电器等的基类。示例代码可能如下所示:
struct port {
//nothing
};
struct power : public port {
bool poweron = true;
};
struct relay : public port {
port* input;
bool on; //will depend on input wire's signal
};
struct wire : public port {
port* input; //input end
port* output; //output end
std::vector<port*> outports; //output sockets for additional branching
std::vector<port*> inports; //input sockets for additional branching
};
struct bit_input : public port {
port* output; //bit input can be vector too
};
struct bit_output : public port {
port* input; //only one input bit to the bit output (lol)
};
int main(void)
{
bit_input bin;
bit_output bout;
wire w0, w1;
power p;
relay r;
////////////////////////////////////////////////////////////////////////////////////////////////
bin.output = &w0; //input wire connected to boolean input's output: ->bin------->
bout.input = &w1; //output wire connected to boolean output's input: ------->bout->
w1.input = &p; //output wire's input end is set to the power supply power------->bout->
w1.output = &bout; //output wire's output end is set to the boolean output
w0.input = &bin; //input wire's input end is set to the boolean input's output
////////////////////////////////////////////////////////////////////////////////////////////////
w0.outports.push_back(&r); //one of input wire's output port is set to the relay; ->bin---|--->
// relay
// power--|---->bout->
w1.inports.push_back(&r); //relay is connected to one of output wire's inut ports too
////////////////////////////////////////////////////////////////////////////////////////////////
r.input = &w0; //relay's input bit is set to input wire
return 0;
};
这只是一个快速的代码,没有用于连接的接口。那么,有没有(当然有)更好的方法来做这种层次结构,有很多链接在一起。这只是一个例子,因为它仍然不处理信号、分支等等......
主要问题是使用指针将部分链接在一起,因为为此我必须在取消引用指针时跟踪类型。所以我也可以为此使用 void 指针......我尝试直接使用指向这些结构的指针,但必须制作模板,例如wire<power_supply, wire<whatever,whatever>> 用于电线输入端可以连接到电源,输出端可以连接到另一根电线。但是电线是一个模板,所以当我想连接多达 1000 根电线时,这并没有带来什么好处。对于需要互相引用的2个以上的类,我还没有找到任何好的解决方案。
【问题讨论】:
-
虽然我并不真正了解/理解问题域,但在我看来,您不需要对电线本身进行建模。每个组件都有指向与其连接的其他组件的指针,通过该指针,它可以从这些连接的组件中获取信息。为了获得这些信息,我可能会尝试使用连接组件可以调用的多态/虚拟函数,从而尝试消除了解取消引用指针的确切类型的需要
-
问题是这样的,更多的类stackoverflow.com/questions/5493745/…。我事先不知道哪个班级会有指向哪个班级的链接。布尔电路就是一个例子,我之前也遇到过这个问题。
标签: c++ class design-patterns