成员变量与成员函数的初始化

Initialization of Member variables vs Member functions

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

尝试使用 c++11 标准编译以下内容失败并显示错误:

class test{
public:
int getId(){
return id;
}
constexpr int id = 5;
};

non-static data member cannot be constexpr;.

我假设上述情况发生,因为类test在编译时尚不存在。

但是,在getId(){下定义constexpr int id = 5;就可以了。 函数getId在编译时可用吗?如果它的类还不存在,它怎么可能可用?

示例 2:

class test{
public:
int getId(){
constexpr int id = 5;
return id;
}
};

是的,该函数在编译时可用。您可以通过使其成为constexpr函数来确认这一点,如下所示。你可以将函数声明为constexpr static,因为它不需要访问任何非静态成员。

class test {
public:
constexpr int getId() {
constexpr int id = 5;
return id;
}
};