会员职能授权

Delegation of Member function

我搜索了很多类似成员函数委托的内容,但没有找到相关内容。可能是我搜错词了...

我尝试做如下事情:

    class Foo1 {
        int bar(int a, int b = 1, bool c = false);
        int bar(int a, bool c);
    }

    // Can I write it like:
    class Foo2 {
        int bar(int a, int b = 1, bool c = false);
        // This line is my question:
        int bar(int a, bool c) : bar(a, 1, c);
    }

我的编译器说只有构造函数接受初始化列表,但我想我在某处读到了类似上面的内容。只有构造函数采用初始化列表的规则有任何例外吗?

错误信息很清楚,你不能在成员函数中做那种委托。

你可以做的只是调用一些成员函数中的其他成员函数,传递一个参数,比如:

class Foo1 {
    int bar(int a, int b = 1, bool c = false);
    int bar(int a, bool c);
}

// Can I write it like:
class Foo2 {
    int bar(int a, int b = 1, bool c = false);

    // Should be inlined by default, but won't hurt to specify it explicitly
    inline int bar(int a, bool c) {
        return bar(a, 1, c);
    }
}

使用两个参数调用 bar 应该不会有任何性能缺陷。

初始化列表用于初始化 class 对象的基类和成员,这只对 class 构造函数有意义。函数不需要初始化(函数参数除外,函数参数会根据每次调用时传递的参数自动初始化)。

但是将一个函数延迟到另一个函数很容易:您只需在第一个函数的主体中调用另一个函数。

class Foo2 {
    int bar(int a, int b = 1, bool c = false);
    int bar(int a, bool c) { return bar(a, 1, c); }
};