我一直在C++开发一个PLC库。该库应包含其他多路复用器块。多路复用器从四个输入中选择一个输入基于两个控制逻辑信号的值:
control_01 | control_02 | output
----------------------------------
0 | 0 | input_01
1 | 0 | input_02
0 | 1 | input_03
1 | 1 | input_04
该库将包含更多的块,然后多路复用器块,例如pid控制器,滤波器、信号发生器等。我决定为所有这些块声明统一接口:
namespace ControlBlocks
{
class ControlBlk{
public:
virtual void Update(void) = 0;
private:
};
}
多路复用器按以下方式实现此接口:
接口:
namespace ControlBlocks
{
class Mux : public ControlBlk{
public:
Mux(uint32_t* const bitsArray, const uint32_t control_01, const uint32_t control_02,
float* const input_01, float* const input_02, float* const input_03, float* const input_04,
float* const output);
virtual ~Mux();
void Update(void);
private:
uint32_t* m_BitsArray;
uint32_t m_Control01;
uint32_t m_Control02;
float* m_Input01;
float* m_Input02;
float* m_Input03;
float* m_Input04;
float* m_Output;
int8_t GetControlValue(uint32_t* const bitsArray, const uint32_t control_01, const uint32_t control_02);
};
}
实现:
ControlBlocks::Mux::Mux(uint32_t* const bitsArray,
const uint32_t control_01, const uint32_t control_02,
float* const input_01, float* const input_02, float* const input_03, float* const input_04,
float* const output):
m_BitsArray{bitsArray},
m_Control01{control_01},
m_Control02{control_02},
m_Input01{input_01},
m_Input02{input_02},
m_Input03{input_03},
m_Input04{input_04},
m_Output{output}{
}
ControlBlocks::Mux::~Mux() {
// TODO Auto-generated destructor stub
}
void ControlBlocks::Mux::Update(void){
uint8_t controlValue = GetControlValue(m_BitsArray, m_Control01, m_Control02);
switch(controlValue){
case 0:
*m_Output = *m_Input01;
break;
case 1:
*m_Output = *m_Input02;
break;
case 2:
*m_Output = *m_Input03;
break;
case 3:
*m_Output = *m_Input04;
break;
}
}
float ControlBlocks::Mux::GetOutput(void){
return *m_Output;
}
int8_t ControlBlocks::Mux::GetControlValue(uint32_t* const bitsArray, const uint32_t control_01, const uint32_t control_02){
uint8_t controlValue = 0;
if(Utils::TestBitSet(bitsArray, control_01)){
controlValue += 1;
}
if(Utils::TestBitSet(bitsArray, control_02)){
controlValue += 2;
}
return controlValue;
}
为了完整起见:
bool Utils::TestBitSet(uint32_t *bitsArray, uint32_t bit){
uint32_t wordValue = *(bitsArray + (bit >> 5));
uint32_t bitPosInWord = (bit - ((bit >> 5) << 5));
return ((wordValue & ((uint32_t)1 << bitPosInWord)) >> bitPosInWord) ? true : false;
}
问题是多路复用器接收指向输入的指针可与另一个模块互连。但在某些情况下,我需要将常量(即编译时已知的常量值(传递到多路复用器中。不幸的是,我不知道如何解决这个问题。有没有人知道如何将指针传递给变量以及编译时常量?
在函数中使用 const 引用,并在调用函数时传递延迟指针或 const 值:
#include <iostream>
void f(const float& value) {
std::cout << value << std::endl;
}
int main() {
float a = 5.2;
float* p = new float(4.3);
const float c = 2.1;
constexpr float cc = 1.2;
f(a);
f(*p);
f(c);
f(cc);
f(5.1);
delete p;
}