2016-01-19 71 views
1

在阅读一个名为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字段”?
+0

看起来好像你正在试图为一个变量使用函数签名。 –

+0

这不是特定于成员函数 - 在C++ 11中,'int f();使用p = int(); p x = f;'g ++给出“错误:函数'int x()'被初始化为一个变量”。 – molbdnilo

回答

3

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

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

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

好的,你直接指出我的理由是什么:我在想'int_property foo'是用'int()const'签名来声明'foo'函数指针,而不是。谢谢。 –