gpt4 book ai didi

c++ - 初始化成员函数字段

转载 作者:行者123 更新时间:2023-11-30 02:34:03 24 4
gpt4 key购买 nike

在阅读名为 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 赋予值(value)“字段”?

最佳答案

int() const 是一个带有 cv-qualifier 的函数类型。声明 int_property top; 声明了一个函数,而不是一个变量。此声明与 int top() const; 具有相同的效果。

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

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

关于c++ - 初始化成员函数字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34878825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com