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是一个常量成员。

好的。我确信我没有错。我稍后会删除这个问题。谢谢您的参与!
发布于 2021-04-13 05:49:23
"const int* x“是一个指向const int的(非常量)指针。因为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网站很有帮助。
https://stackoverflow.com/questions/67065762
复制相似问题