指针和引用作为const对象的成员变量

编程入门 行业动态 更新时间:2024-10-25 00:33:40
本文介绍了指针和引用作为const对象的成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下代码可以正常编译。但是我不知道这是否合法的C ++。因此,更具体地说,如果我有一个const对象,是否可以通过该对象的指针/引用来修改变量?

The following code compiles fine. However I wonder if it is legal C++. So more specific, if I have a const object, am I allowed to modify variables through pointers/references of that object?

class Foo { public: int* a; int& b; Foo(int* _a, int& _b) : a(_a), b(_b) {} }; int main ( int argc, char* argv[] ) { int x = 7; const Foo bar(&x, x); *bar.a = 3; //Leagal? bar.b = 7; //Legal? return 0; }

推荐答案

这是合法的,因为const-类的级别表示类成员是恒定的。 a 是一个指针,因此指针指向的地址是恒定的,但存储在该地址的值不必是恒定的。

It's legal, as const-ness of the class means that the class member is constant. a is a pointer, so the address the pointer points to is constant, but the value stored at that address need not be.

因此, bar.a 实际上是 int * const ,而不是 int const * 。

Hence bar.a is effectively an int * const, not an int const *.

由于初始化后,无论如何都不能引用另一个实体,对于 bar.b 是否将 bar 声明为 const 。

As, after initialization, a reference cannot be made to refer to another entity anyway, it does not matter for bar.b whether bar is declared const or not.

指针的常量变量是常量指针,而不是指向常量的指针。引用的常量变体是引用,而不是对常量的引用。

The constant variant of a pointer is a constant pointer, not a pointer to a constant. The constant variant of a reference is a reference, not a reference to a constant.

小题外话:无论如何,在与const-ness有关的成员中,您都应谨慎对待引用,因为以下内容可能会编译

Small digression: You should be careful with references as members anyway in connection with const-ness, as the following will probably compile

struct Y { int m_a; }; struct X { const Y & m_y; X (const Y & y) : m_y (y) { } }; Y y; y.m_a = 1; X x (y); // or const X x (y) -- does not matter // X.m_y.m_a == 1 y.m_a = 2; // now X.m_y.m_a == 2, although X.m_y is supposed to be const

由于可以将指向非const的指针分配给指向const的指针,因此可以使用指针构建类似的示例。请记住, const 仅保证您不会通过此非常大的变量来修改变量,它不能保证完全不修改变量的内容。

As it is possible to assign a pointer to non-const to a pointer to const, you can build an analogous example with pointers. Remember that const does only guarantee that YOU will not modify a variable via this very variable, it cannot guarantee that the contents of the variable are not modified at all.

更多推荐

指针和引用作为const对象的成员变量

本文发布于:2023-11-02 13:54:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552580.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   变量   对象   成员   const

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!