定义:在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。this 指针是所有成员函数的隐含参数。因此,在成员函数内部,它可以用来指向调用对象。
编译器针对程序员自己设计的类型分三次编译
第一 : 识别和记录类体中属性的名称,类型和访问限定,与属性在类体中的位置无关.
如 class CGoods 中的Name,Amount,Price, Total value :
第二 : 识别和记录类体中函数原型(返回类型 + 函数名 + 参数列表),形参的默认值,访问限定。不识别函数体。
第三 : 改写在类中定义函数的参数列表和函数体,改写对象调用成员函数的形式: +this
class CGoods
{
private:
char Name[21];
int Amount;
float Price;
float Total;
public:
void RegisterGoods(char[], int, float); //输入数据
void GetName(char[]); //读取商品名
int GetAmount(void); //读取商品数量
float GetPrice(void); //读取商品单价
void CountTotal(void); //计算商品总价值
float Gettotal(void)
{
return Total;
}
};
void CGoods::RegisterGoods(char name[], int amount, float price)
{
strcpy_s(Name,len, name);
Amount = amount;
Price = price;
}
void CGoods::CountTotal(void)
{
Total = Price * Amount;
}
void CGoods::GetName(char name[])
{
strcpy_s(Name, len, name);
}
int CGoods::GetAmount(void)
{
return (Amount);
}
float CGoods::GetPrice(void)
{
return (Price);
}
float CGoods::Gettotal(void)
{
return (Total);
}
改写之后的代码:
//this指针的作用:
//编译器针对程序员自己设计的类型分三次编译
//第一 : 识别和记录类体中属性的名称,类型和访问限定,与属性在类体中的位置无关.
//如 class CGoods 中的Name,Amount,Price, Total value :
//第二 : 识别和记录类体中函数原型(返回类型 + 函数名 + 参数列表),形参的默认值,访问限定。不识别函数体。
//第三 : 改写在类中定义函数的参数列表和函数体,改写对象调用成员函数的形式:+this
class CGoods
{
private:
char Name[LEN];
int Amount;
float Price;
float Total_value;
public:
void RegisterGoods(const char*, int, float);
//void RegisterGoods(CGoods* this,const char*, int, float);
void CountTotal(void);
//void CountTotal(CGoods* const this);
void GetName(char*,int);
int GetAmount(void);
float GetPrice(void);
//float GetTotal_value(CGoods* const this)
float GetTotal_value(void)
{
return this->Total_value;
}
};
//void CGoods::RegisterGoods(CGoods *this,const char*name, int amount, float price)
void CGoods::RegisterGoods(const char*name, int amount, float price)
{
strcpy_s(this->Name, LEN, name);
this->Amount = amount;
this->Price = price;
}
//void CGoods::CountTotal(CGoods*this)
void CGoods::CountTotal(void)
{
this->Total_value = this->Amount * this->Price;
}
void CGoods::GetName(char*name,int n)
{
strcpy_s(name,n, Name);
}
int CGoods::GetAmount()
{
return Amount;
}
float CGoods::GetPrice()
{
return Price;
}
//float CGoods::GetTotal(CGoods *this)
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 指针指向调用对象。如果方法需要引用整个调用对象,则可以使用表达式this。在函数的括号后面使用 const 限定符将 his 限定为 const,这样将不能使用 this 来修改对象的值。
然而,要返回的并不是 this,因为 his 是对象的地址,而是对象本身,即*this(将解除引用运算符*用于指针,将得到指针指向的值)。现在,可以将*this 作为调用对象的别名来完成前面的方法定义。