重载函数而不重写其整个定义

时间:2015-02-12 17:32:32

标签: c++ overloading

请参阅以下示例:

class bar{
    private:
        unsigned _timeout;
    public:
        bool foo(unsigned arg);
        bool foo(unsigned arg, unsigned timeout);
};

bool bar::foo(unsigned arg){
    /*50 lines of code*/
    if (_timeout > 4)
       //...
}

bool bar::foo(unsigned arg, unsigned timeout){
    /*50 lines of code*/
    if (timeout > 4)
       //...
}

正如您所看到的,这些函数只有一行不同 - 第一行使用私有成员_timeout,第二行检查作为参数传递的变量timeout。这里的问题是,我必须重写整个~50行代码才能重载此函数。有没有解决方法?

3 个答案:

答案 0 :(得分:3)

两种选择:将常用功能提取到自己的功能中(重构),或者让一个功能调用另一个功能。

在您的情况下,您可以像这样定义第一个重载:

bool bar::foo(unsigned arg) {
    return foo(arg, _timeout);
}

一般来说,重构也是一种很好的方法:

void bar::foo_inner(unsigned arg) { // or however it should be declared
    // 50 lines of code
}

bool bar::foo(unsigned arg) {
    foo_inner(arg);
    if (_timeout < 4)
        ...
}

bool bar::foo(unsigned arg, unsigned timeout) {
    foo_inner(arg);
    if (timeout < 4)
        ...
}

答案 1 :(得分:2)

这个怎么样:

bool bar::foo(unsigned arg)
{
    return foo(arg, _timeout);
}

答案 2 :(得分:0)

根据另外两个私有函数实现这两个函数:

class bar{
    private:
        unsigned _timeout;

        void fooImplBegin(unsigned arg);
        bool fooImplEnd(unsigned arg);
    public:
        bool foo(unsigned arg);
        bool foo(unsigned arg, unsigned timeout);
};

void bar::fooImplBegin(unsigned arg) {
    /*50 lines of code */
}

bool bar::fooImplEnd(unsigned arg) {
    /* more lines of code, returning something */
}

bool bar::foo(unsigned arg){
    fooImplBegin(arg);
    if (_timeout > 4)
       //...
    return fooImplEnd(arg);
}

bool bar::foo(unsigned arg, unsigned timeout){
    fooImplBegin(arg);
    if (timeout > 4)
       //...
    return fooImplEnd(arg);
}