我有点困惑为什么这个代码编译和运行:
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.
更多推荐
发布评论