C++笔记6-this指针

本文深入解析了C++中this指针的概念及其使用场景,包括其在成员函数中的默认行为,以及如何通过const限定符改变其属性。同时,对比了函数返回引用与返回元素的区别,阐述了它们在类实例操作中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、C++类的普通成员函数都隐式包含一个指向当前对象的this指针,但静态成员函数不包含指向具体对象的指针。
2、this指针本质上是一个常指针 :类型 *const p;
3、员函数后面加const 修饰的不是函数,修饰的是隐藏的this指针,则此时该成员函数的this指针为指向常量的常指针:
const 类型 *const p;
class Test
{
public:
Test(int k)
{
this->m_k = k;
this->m_q = 0;
}
Test(int k, int q)
{
this->m_k = k;
this->m_q = q;
}
int getK() const // int getK(const Test *const this) // this 是一个常指针
{
//this++;
//this->m_k = 0; 在成员函数后面加const 修饰的不是函数,修饰的是隐藏的this指针
return this->m_k;
}
private:
int m_k;
int m_q;
};

4、函数返回引用与函数返回元素区别
函数返回引用(类的引用)可以继续调用类内函数和公有变量,函数返回元素无法继续调用。
class Test
{
public:
Test()
{
this->a = 0;
this->b = 0;
}
Test(int a, int b)
{
this->a = a;
this->b = b;
}
void printT()
{
cout << "a = " << a << ", b = " << b << endl;
}
Test TestAdd02(Test &another)//函数返回元素
{
//Test temp(this->a + another.getA(), this->b + another.getB());
Test temp(this->a + another.a, this->b + another.b);
return temp;
}
Test & TestAdd04(Test &another)//函数返回引用
{
this->a += another.a;
this->b += another.b;
//返回自己
return *this;
}//temp引用 = *this
private:
int a;
int b;
};
int main(void)
{
Test t1(10, 20);
Test t2(100, 200);
Test t5 = t1.TestAdd02(t2); //创建临时的开销
**(t1.TestAdd04(t2)).printT(); //t1的别名,其中t1.TestAdd04(t2)就返回t1本身
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值