1

我是 C++ 新手,我想知道我们是否可以接受任何结构作为我们的方法参数。

情况就是这样:我有一个类(比方说hw_manager)与硬件类(比方说)交互hw_device1。目前hw_manager会调用 的方法,方法hw_device1的结果会通过 struct 参数返回(将 struct 参数作为引用发送,并更改引用参数的值)。

在 C++ 中代码应该是这样的:

struct sSensorStatus {
    unsigned char sensor1;
    unsigned char sensor2;
};

bool checkSensorStatus(struct sSensorStatus &status) {
    // Change the status here
}

现在,由于硬件发生了变化,我需要创建一个新类,假设hw_device2它具有完全不同的操作。

struct sHardwareStatus {
    unsigned char loader;
    unsigned char transport;
    unsigned char ejector;
    unsigned char mouth;
};

bool checkHardwareStatus(struct sHardwareStatus &status) {
    // Change the status here
}

hw_manager我打算实现一个接口,而不是更改其中的代码(这将影响该层之上的代码),假设IHardware它具有doAction方法。这个想法是这样的:

bool doAction(int cmdID, ????) {
    // switch case cmdID
    // based on the cmdID, type cast the ???? into the struct
}

我应该放什么????接受任何类型的结构?我可以在 C++ 中做到这一点吗?

谢谢

编辑

在硬件内部,我还会有另一个结构,所以我认为使用模板不合适。抱歉,澄清晚了。

4

4 回答 4

4

只需使用多态性。为所有设备创建一个基本类,并将指向它的指针或引用作为参数传递给方法doAction

编辑(感谢 Koushik 对 elyashiv 的回答的评论):

实际上,更好的解决方案是使方法 doAction 成为所有设备的基类中的虚拟方法,并且根本不向它传递任何东西。

于 2013-04-09T07:49:41.063 回答
2

你可以这样做:

struct IHardware{virtual doAction() = 0;} 

现在继承它

struct sHardwareStatus : public IHardware
{/*implementation with implementation for doAction()*/
    unsigned char loader;
    unsigned char transport;
     unsigned char ejector;
    unsigned char mouth;
     /*provide concrete definition for bool doAction() here*/
}

也为

srtuct sSensorStatus : public IHardware
{/*implementation with implementation for doAction()*/
    unsigned char sensor1;
    unsigned char sensor2;
    /*provide concrete definition for bool doAction() here*/
}

现在,当您从接口继承新硬件时,然后为该类编写结构。我想doAction()每个硬件都会有所不同。

于 2013-04-09T08:09:19.870 回答
1

如果你只有几个结构和函数要调用,你可以使用模板和模板特化:

template<typename T>
bool doAction(T& s)
{
    return false;
}

template<>
bool doAction(sSensorStatus& status)
{
    return checkSensorStatus(status);
}

template<>
bool doAction(sHardwareStatus& status)
{
    return checkHardwareStatus(status);
}

如您所见,您实际上并不需要该cmdID标志,编译器将通过单独使用结构类型自行解决。

于 2013-04-09T07:51:06.440 回答
1

你应该使用继承。
类似的事情已经到位:

struct HardwareStatusInterface{};
struct sHardwareStatus : public HardwareStatusInterface
 {
    unsigned char loader;
    unsigned char transport;
    unsigned char ejector;
    unsigned char mouth;
};
struct sSensorStatus : publc HardwareStatusInterface
 {
    unsigned char sensor1;
    unsigned char sensor2;
};

和功能:

bool doAction(int cmdID, HardwareStatusInterface &HI) {
    // switch case cmdID
    // based on the cmdID, type cast the ???? into the struct
}
于 2013-04-09T07:52:42.670 回答