繁体   English   中英

初始化成员函数字段

[英]Initializing member functions fields

在阅读一篇名为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(only '= 0' is allowed) before ';' token (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_property

int() const是具有cv-qualifier的函数类型。 声明int_property top; 声明一个函数,而不是一个变量。 该声明与int top() const;具有相同的效果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 ,或者至少检查编译器当前支持的功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM