需要const成员函数澄清(const member function clarification needed)

编程入门 行业动态 更新时间:2024-10-14 08:27:45
需要const成员函数澄清(const member function clarification needed)

我有点困惑为什么这个代码编译和运行:

class A { private: int* b; public: A() : b((int*)0xffffffff) {} int* get_b() const {return this->b;} }; int main() { A a; int *b = a.get_b(); cout<<std::hex<<b<<endl; return 0; }

运行此代码的输出也是FFFFFFFF ......我意外。 不应该 - this->b返回const int*因为它在const成员函数中? 因此return行应该生成一个编译器转换错误,试图将const int*为int*

显然,我对const成员函数的含义有所了解。 如果有人能帮我弥合这个差距,我会很感激。

I'm a little confused as to why this code compiles and runs:

class A { private: int* b; public: A() : b((int*)0xffffffff) {} int* get_b() const {return this->b;} }; int main() { A a; int *b = a.get_b(); cout<<std::hex<<b<<endl; return 0; }

Output of running this code is FFFFFFFFas well... unexpected by me. Shouldn't this->b return const int* since it is in a const member function? and therefore the return line should generate a compiler-cast error for trying to cast const int* to int*

Obviously there's a gap here in my knowledge of what const member functions signify. I'd appreciate if someone could help me bridge that gap.

最满意答案

不,该成员是一个int* const (从const函数中可以看出),这是完全不同的。

指针是const,而不是指向的对象。

No, the member is an int* const (as seen from the const function), which is totally different.

The pointer is const, not the object pointed to.

更多推荐

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

发布评论

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

>www.elefans.com

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