成员变量与成员函数的初始化
Initialization of Member variables vs Member functions
尝试使用 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;
}
};
相关文章:
- C++成员初始化
- c++构造函数成员初始化:传递参数
- C++正确的指针成员初始化
- 将另一个类的对象传递到当前类C++的构造函数中(不是成员初始化)
- WinLamb 错误:成员初始化非法
- 使用其他成员初始化结构的成员?
- C++模板类静态成员初始化
- 解释了构造函数成员初始化列表
- 如何在成员初始化列表中声明共享指针
- C++入门5版:使用get成员初始化另一个与shared_ptr无关的对象
- C++11 默认类成员初始化与初始值设定项列表同时
- 调用非默认构造函数作为成员初始化
- C++模板成员初始化:用右值移动构造,但用左值移动引用
- 类成员初始化C++
- 在成员初始化列表中,我可以创建对列表中不在列表中的成员变量的引用
- C :(不重复)积分静态成员初始化(不仅是声明!),导致链接器错误,原因
- 如何调用成员初始化器列表中参考成员的构造函数
- C 构造函数采用成员初始化器
- 与其他静态const成员初始化静态常量成员
- 静态内联成员初始化顺序