this指针

this指针传递的是当前对象的指针,这样每个对象操作自己的成员变量

  • this指针是常量指针,不可修改

class Goods
{
public:
	Goods(int w):m_weight(w)
	{
	}

	int Get()
	{
		this++;  //报错,必须是可修改的左值 ,证明传递的是: Goods* const this
		return m_weight;
	}

private:
	int m_weight;

};


成员函数后加const

  • 如果一个成员函数后面加const修饰,修饰的是this指针,表示不可以通过this指针修改其对象内容
class Goods
{
public:
	Goods(int w):m_weight(w)
	{
	}

	int Get()const //不能通过this进行修改值, 传递的是: const Goods* const this
	{
		m_weight++;   //报错,this->m_weight++; 
		return m_weight;
	}

private:
	int m_weight;

};

  • 使用情况:注意27行的注释
#include "stdafx.h"
#include <iostream>
#include <string.h>

using namespace std;


class Student
{
	friend Student operator+(const Student& s1, const Student& s2);
public:
	Student(int id) :m_id(id) {}

	int GetID()const
	{
		return m_id;
	}


private:
	int m_id;
};


Student operator+(const Student& s1,const Student& s2)
{
	Student tmp(s1.GetID()+s2.GetID()); //如果Student::GetID后面不加const报错,因为将GetID(Student* const s),将const s1赋值給s报错

	return tmp;
}



int main(void)
{
	Student A(1);
	Student B(2);

	Student C = A + B;
	cout << C.GetID() << endl;
    return 0;
}




静态成员函数没有this指针

  • 静态成员函数只能访问静态成员变量,因为静态成员函数不属于对象,所以没有this指针


返回对象本身用 *this

#include "stdafx.h"
#include <iostream>

using namespace std;

class Goods
{
public:
	Goods(int w):m_weight(w)
	{
	}

	Goods& Add(Goods& another) //返回是自身引用,还可以做左值
	{
		m_weight+=another.m_weight;
		return *this;
	}
	void Print()
	{
		cout << m_weight << endl;
	}

private:
	int m_weight;

};


int main(void)
{
	Goods A1(100);
	Goods A2(100);
	Goods A3(100);

	A1.Add(A2).Add(A3);

	A1.Print(); //300
	
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值