c++ - C++ 中的常量成员是什么?
问题描述
class Foo
{
public:
const int a;
const int* x;
int* const y;
Foo() : a{ 0 }, y{ new int(20) } {
x = new int(10);
}
};
int main()
{
Foo f;
// f.a = 100; // cannot
f.x = new int(100);
// f.y = new int(100); // cannot
}
当const int a
被定义为类的字段时,它被称为常量成员。它必须在初始化器列表中初始化,之后不能更改。
const int* x
(与 相同int const* x
)和怎么int* const y
样?哪一个应该被称为常量成员?如果“常量成员”被定义为必须在初始化列表中初始化并且之后不能更改的字段,则常量成员是y
而不是x
。我在这里错了吗?
编辑
根据 IntelliSense,y
是一个常量成员。
好的。我确信我没有错。我会尽快删除这个问题。感谢您的参与!
解决方案
“const int* x”是指向 const int 的(非 const)指针。由于 x 是非常量的,因此不需要在构造时对其进行初始化。
这里有些例子:
class C
{
public:
C() :
const_int(1),
const_int_again(2),
const_ptr_to_non_const_int(nullptr),
const_ptr_to_const_int(nullptr)
{}
private:
const int const_int;
int const const_int_again;
const int* ptr_to_const_int; // Doesn't need initialized
int const* ptr_to_const_int_again; // Doesn't need initialized
int* const const_ptr_to_non_const_int;
const int* const const_ptr_to_const_int;
int const* const const_ptr_to_const_int_again;
};
您可能会发现cdecl.org网站很有帮助。
推荐阅读
- java - 使用 spring-cloud-gateway 时考虑 @RequestBody 参数
- javascript - Express.Router、body-parser 和 post request body
- docker - 从 Azure Function 中的 ACR 提取图像时出错
- bash - 如何在sh、ksh、csh下使用bash变量前缀
- python - 使用 Beautiful Soup 在元内容中查找对应的兄弟姐妹
- python - 如何从直接在模板中而不是在forms.py中编写的表单中获取数据?
- javascript - 多级表行展开折叠反应
- ios - WKWebKit 实现(Objective-C)
- python-3.x - python中'part%04d'的含义
- reactjs - 上下文 API history.listen 无法读取未定义的属性“listen”