C++ this与const,const_cast,static_cast的关系

来源:互联网 发布:淘宝采集软件合法吗 编辑:程序博客网 时间:2024/05/22 12:08

一、整体代码

#include <iostream>using namespace std;class CCTest {public:   void setNumber( int );   void printNumber() const ;private:   int number;};void CCTest::setNumber( int num ) { number = num; }void CCTest::printNumber() const {   cout << "\nBefore: " << number;   const_cast< CCTest * >( this )->number--;   cout << "\nAfter:" << number;}int main() {   CCTest X;   X.setNumber( 8 );   X.printNumber();   cout << "\n" <<endl;}

二、运行结果如下:



三、解释

      如果方法声明为const,那么实现的时候一定要加上const。

      在const方法中this 指针的数据类型为 const CCTest *,只能调用const的方法和成员变量。

      如果想调用非const的方法和成员变量,那么就要const_cast< CCTest * >( this ),其中this类型为const CCTest* ,改变后为CCTest*,就可以使用非const的方法和成员变量了。

      在非const方法中this指针的数据类型为CCTest *可以调用所有的方法和成员变量。如果一个方法同时有const和非const版本,优先调用非const版本。

      

四、static_const

RefBase* RefBase::weakref_type::refBase() const{    return static_cast<const weakref_impl*>(this)->mBase;}

      如果在const方法中,由于this为const RefBase::weakref_type类型,转换为子类const RefBase::weak_impl类型。

RefBase* RefBase::weakref_type::refBase() {    return static_cast<weakref_impl*>(this)->mBase;}
      如果没在const方法中,由于this为RefBase::weakref_type类型,转换为子类RefBase::weak_impl类型。

0 0
原创粉丝点击