您的位置:首页 > 编程语言 > C语言/C++

C++ primer 5th edition:7.1.2节(关于this指针;关于const member functions)

2014-02-22 15:52 645 查看
一:关于this

有一个类Sales_data,有一个这个类的object:Sales_data total;

当我们使用这个object中的一个member函数时,例如(total.isbn()),compiler会implicitly传给isbn函数total这个object的地址,用于初始化isbn函数中隐藏的this这个parameter。

compiler的这个操作造成的效果是:在isbn函数中可以refer directly to the members of the object "this" points to, without having to use "."

**************************************************************************************************************************************

二:关于类中出现的在函数的parameter list后面加上“const”的意义:std::string isbn() const;

首先,the purpose of that "const" is to modify the type of the implicit "this" pointer.

也就是说,这个“const”就是针对“this”指针存在的;

第二,by default,这个“this”指针is a const pointer to the
nonconst version of the class type.(例如Sales_data *const)。这种默认的类型就带来一个效果:我们不能"bind ‘this’ to a const object",意思就是为了类型匹配,如果一个object是const类型的,那我们就不能调用它的成员函数了!

所以,为了类型匹配,当一个object是const类型的,我们应该规定传给这个object的member function的“this”指针类型不能是default的,而应该是一个指向对应const类的const指针。

但是!问题在于我们调用isbn函数时,“this”指针由compiler implicitly pass给isbn函数的,我们看不到“this”,也就没法直接规定它的类型哦!

因此,C++就给了一个语法,如果在member function的parameter list 后面额外加上一个keyword“const”,就是告诉compiler该给“this”的类型定为const pointer to a const object了!

第三:这种做法带来了一个额外的效果。由于this指针指向的是const object,所以收到这个“this”指针的member function 就没有能力做改变object的事情了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: