关于this指针的理解

1.初探this指针

定义:this:储存当前对象的地址,可以使用 * 来获得指向的对象

实验程序:将一个对象的数据成员拷贝至另一个对象中,拷贝成员后返回该对象
声明
class Triangular
{
public:
    Triangular();
    Triangular(int, int);
    int length() const{ return _length;}
    int beg_pos() const{ return _beg_pos;}
    Triangular& copy( const Triangular &rhs);
private:
    int _length;
    int _beg_pos;
    mutable int _next;
};

成员函数的实现

Triangular::Triangular()
{
    _length = 1;
    _beg_pos = 1;
    _next = 0;
}
Triangular::Triangular( int len, int beg)
{
    _length = len;
    _beg_pos = beg;
    _next = beg-1;
}
Triangular& Triangular::copy( const Triangular &rhs)
{
    //check that the two object are not the same
    if( this != &rhs )
    {
        _length = rhs.length();
        _beg_pos = rhs.beg_pos();
        _next = rhs.beg_pos() - 1;
    }
    return *this;
}

主函数

#include "ClassTest.h"
int main()
{
    Triangular tri(3, 5);
    Triangular tri1;
    tri1.copy( tri );
    return 0;
}

运行过程


分析
由于调用的copy函数是对象 tri1中的成员函数因此 this指针存储的是 tri1的地址。在函数中使用的变量或者函数实际的形式为
_length 等价于 this->_length
fun() 等价于 this->fun()

2.在什么时候this 指针会发生改变

实验程序(部分代码),github源码:点击打开链接

BinaryTree.cpp

//wrong function format, the return should place
//in the front of class
template<typename elemType>
void BinaryTree<elemType>::
insert(elemType elem)
{
	if (!_root)
		_root = new BTnode<elemType>(elem);
	else
		_root->insert_value(elem, _root);
}
//root->_lchild: address or value?
template<typename valType>
void BTnode<valType>::
insert_value(valType &elem, BTnode *root)
{
	if (elem == _val)
    {
        _cnt++;
        return;
    }
	else
	if (elem < _val)
	{
		if (_lchild)
			root->insert_value(elem, _lchild);
		else
			_lchild = new BTnode(elem);
	}
	else
	{
		if (_rchild)
			root->insert_value(elem, _rchild);
		else
			_rchild = new BTnode(elem);
	}
}

main.cpp

int main()
{
	BinaryTree<int> ibt;
	ibt.insert(23);
	ibt.insert(3);
	ibt.insert(1);
	ibt.insert(10);
	ibt.insert(33);
    ...
}


运行过程


分析
对于this指针发生变化的理解主要是需要知道什么是当前对象
当插入第三个值1时,有三个地址是有效的:23fefc、3f0e38、3f0e60
23fefc 是ibt对象的地址,类型为BinaryTree。它的成员只有根节点 BTnode* _root,成员函数有insert(elem)
3f0e38 是根节点23的地址,类型为BTnode,它存储了实际的值,及左右叶节点的地址
3f0e60 是叶节点3的地址,类型为BTnode

当继续插入叶节点1时 进行如下过程


总结
进入成员函数后会有this指针,因此"当前"是针对函数来说的,在递归调用的时候 如果只使用fun(),则默认的进行的是 this->fun(),因为fun()的作用域没有改变,所以this指针永远不会变。 只有使用 pointer->fun()此时fun()的作用域发生了改变,this指针才会改变。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值