初始化成员函数字段

Initializing member functions fields

本文关键字:数字段 函数 成员 初始化      更新时间:2023-10-16

在阅读一篇名为Abominable Functions的C++1z论文时,我发现了以下代码:

class rectangle {
    public:
    using int_property = int() const;  // common signature for several methods
    int_property top;
    int_property left;
    int_property bottom;
    int_property right;
    int_property width;
    int_property height;
    // Remaining details elided
};

我以前从未见过这样的代码(论文本身指出找到这样的代码非常奇怪),所以我想尝试这种方法并为这些int_property赋予值:

class rectangle {
    int f() const { return 0; }
    public:
    using int_property = int() const;  // common signature for several methods
    int_property top = f; // <--- error!
    int_property left;
    int_property bottom;
    int_property right;
    int_property width;
    int_property height;
    // Remaining details elided
};

在我上面的修改中,编译器抱怨f(only '= 0' is allowed) before ';' token;我的其他尝试是:

class rectangle {
    int f() const { return 0; }
    public:
    using int_property = int() const;  // common signature for several methods
        // invalid initializer for member function 'int rectangle::top() const'
        int_property top{f};
        int_property left{&f};
        // invalid pure specifier (only '= 0' is allowed) before ';' token
        int_property bottom = f;
        int_property right = &f;
        int_property width;
        int_property height;
        // class 'rectangle' does not have any field named 'width'
        // class 'rectangle' does not have any field named 'height'
        rectangle() : width{f}, height{&rectangle::f} {}
};

所以问题是:

  • 我应该怎么做才能使所有int_property"字段"都指向一个函数?
  • 如何为所有int_property"字段"赋予价值?
int() const

带有 cv 限定符的函数类型。声明int_property top;声明函数,而不是变量。此声明与 int top() const; 具有相同的效力。

与其他成员函数一样,您可以通过提供函数定义来定义它们。

int rectangle::top() const {
    return 0;
}

该论文在2015-11-10 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/作为提案 #P0172R0 引入。我相信您正在使用当前不支持此功能的编译器,但您可以稍后:)检查。此外,阅读当前的标准 http://open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf,或者至少检查编译器当前支持的功能,可能会很有趣。