如何为C函数建模OO样式接口?

时间:2009-05-18 10:42:43

标签: c++ oop

我有一个C模块,它是由Real-time Workshop基于Simulink模型创建的。 该模块提供三种公共功能:

int init();
int calc(double *inputarray, double *outputarray);
int term();

根据outputarray的内容,我可以建模一个名为OutputThing的类。

我想将这些函数集成到一个名为WrapperModule的包装类中。 现在我有一个看起来像这样的课程:

class WrapperModule {
public:
    int initialize();
    OutputThing calc(...);
    int terminate();
};

我的问题是,如何正确设计calc()函数的包装器方法。我想避免 创建一个以数组/向量作为单个参数的方法。但要确定正确的论点 从向量是棘手的,我不喜欢有一个方法有6个或更多的参数。

Bertrand Meyer在他的OOSC书中建议使用setter方法。类似的东西:

class WrapperModule {
public:
    int initialize();
    void set_foo(double f);
    void set_bar(double b);
    OutputThing calc();
    int terminate();
};

有什么想法吗?我不确定哪种方法会更好。

1 个答案:

答案 0 :(得分:3)

如果您还能将inputarray抽象为InputThing课程,我建议如下。这也更好地使用C ++构造/销毁来封装初始化/终止。

class WrapperModule {
public:
    // Calls init()
    WrapperModule();

    // Calls term()
    ~WrapperModule();

    // Calls calc()
    OutputThing calculate(const InputThing& inputThing);
};

如果有必要,InputThing可以使用accessor和mutator(get / set)函数来防止它需要一个带有许多参数的构造函数。