this指针

如果的对象独立安排内存,每个对象都由数据和代码构成,方法在代码区,对象的数据在栈区,对象数量过多的话,太过消耗内存。

所以使用个对象的代码区共用的方案。只消耗了一个指针的内存,节省了大量的空间。

this指针的作用:
编译器针对程序员自己设计的类型分三次编译。
第一:识别和记录类体中属性的名称,类型和访问限定,与属性在类体中的位置无关。
如 class CGoods 中的Name,Amount, Price, Total_value;
第二:识别和记录类体中函数原型(返回类型+函数名+参数列表),形参的默认值,访问限定。不识别函数体。
第三:改写在类中定义函数的参数列表和函数体,改写对象调用成员函数的形式;
示例:

class CGoods
{
private:
char Name[21];
int Amount;
float Price;
float Total_value;
public:
//void RegisterGoods(CGoods * const this,char [],int,float);
void RegisterGoods(char [], int,float);
//void CountTotal(CGoods * const this);
void CountTotal();
};
//void CGoods::RegisterGoods(CGoods * const this,char name[], int amount,float price);
void CGoods::RegisterGoods(char name[],int amount,float price)
{
strcpy(this->Name, name);
this->Amount = amount;
this->Price = price;
}
// void CGoods::CountTotal(CGoods * const this);
void CGoods::CountTotal()
{
this->Total_value = this->Price * this->Amount;
}
int main()
{
CGoods tea;
CGoods book;
tea.RegisterGoods("black_tea", 12, 560);
// RegisterGoods(&tea,"black_tea",12,560);
tea.CountTotal();
// CountTotal(&tea);
book.RegisterGoods("Thinking In C++", 20, 128);
// RegisterGoods(&book,"Thinking In C++",20,128);
book.CountTotal();
// CountTotal(&book);
return 0;
}

从底层来讲实际是当前对象的地址传递给成员方法

this指针关键:识别对象,节省空间

同时为了防止给this指针置空,实际加了const:*const this

另外在成员函数才会进行改写,全局函数不需要进行改写,没有this指针。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值