初始化成员函数字段
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
;我的其他尝试是:
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,或者至少检查编译器当前支持的功能,可能会很有趣。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 我想要一个改变数组快速排序的2个数字的函数
- 使用enable_if匹配数字作为函数参数
- 如何将数字作为函数参数C 传递到向量
- 是否有适用于迭代器的数字解析函数
- Visual Studio 2015中的命令参数字段
- 每个呼叫都会生成不同数字的函数:我应该通过引擎,分配还是两者兼而有之
- 如何创建一个根据概率选择数字的函数
- 使字段函数泛型
- 将排序的数字从函数写出到文本文件
- 确定 int 是否包含特定数字的函数出现问题
- 初始化成员函数字段
- 声明为void的变量或字段(函数)
- 使用递归的c++数字模式函数
- FP号码的指数字段不是我预期的,为什么?
- c++在模块间共享数组元素,仅对少数字段具有const性
- Setw()不影响读取整数字段
- 是否可以将数组数字作为函数来执行?
- C++:如何将 N 参数传递给 N 可以是 0 >任意数字的函数?(该函数已作为外部库的一部分存在)
- 如何设置ostream的指数字段的宽度