用C语言的编写方式来谈对C++中隐藏指针this的认识
首先我们来看一组C++的程序
#include<iostream>
using namespace std;
class CGoods
{
public:
/////////////////////////////////所给参数一样 前后都是Name///////////////////////////
void RegisterGoods(char Name[],int Amount,float Price)
{
strcpy(this->Name,Name);
this->Amount=Amount;
this->Price=Price;
}
///////////////这段代码和以上的可以进行替换,主要看参数是否一样(这是参数不一样的)///////////////////////////////
void RegisterGoods(char name[],int amount,float price)
{
strcpy(name,Name);
amount=Amount;
price=Price;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
void CountTotal(void);
void GetName(char name[])
{
strcpy(name,Name);
}
int GetAmount(void);
float GetPrice(void);
float GetTotal_value(void);
private:
char Name[21];
int Amount;
float Price;
float Total_value;
};
/*
void CGoods::RegisterGoods (char name[],int amount,float price)
{
strcpy(Name,name);
Amount=amount;
Price=price;
}
*/
void main()
{
char name[21];
CGoods c1,c2;
c1.RegisterGoods ("c++",15,30);
c2.RegisterGoods ("JAVA",20,30);
c1.GetName(name);
cout<<name<<endl;
c2.GetName(name);
cout<<name<<endl;
}
接下来我们 再看一段改写后的程序 和C语言中统一起来看
#include<iostream>
using namespace std;
//首先识别类名CGoods;
//然后识别所有的数据成员;
//最后再识别函数,改写函数;
class CGoods
{
public:
//当主函数的程序运行到这一步的时候会产生
//一个This指针。记住之前返回对象的地址,等同用This改写函数
//void RegisterGoods(CGoods *const this,char Name[],int Amount,float Price)//在这块之后this指针是不可以被改变的所以要加一个const
void RegisterGoods(char Name[],int Amount,float Price)
{
strcpy(this->Name,Name);
this->Amount=Amount;
this->Price=Price;
}
void CountTotal(void);
void GetName(char name[])
{
strcpy(name,Name);
}
int GetAmount(void);
float GetPrice(void);
float GetTotal_value(void);
private:
char Name[21];
int Amount;
float Price;
float Total_value;
};
/*
void CGoods::RegisterGoods (char name[],int amount,float price)
{
strcpy(Name,name);
Amount=amount;
Price=price;
}
*/
void main()
{
char name[21];
CGoods c1,c2;
//RegisterGoods (&c1,"c++",15,30);
c1.RegisterGoods ("c++",15,30);
//RegisterGoods (&c2,"c++",15,30);
c2.RegisterGoods ("JAVA",20,30);
//GetName(&c1,name);
c1.GetName(name);
cout<<name<<endl;
//GetName(&c2,name);
c2.GetName(name);
cout<<name<<endl;
}
这就是所谓的this 指针 ,同C语言中的传参时,需要把地址传给参数统一起来,并且注意在计算机传过去This指针后这个指针是*const this 表示This所指的东西在下面的程序中是不可以被改变的。
用C语言的方式来理解C++ 中一些高级函数会让人印象更加深刻。