创建的每个对象里面既有数据成员,也有成员方法。但是我们知道相同类型的对象的成员方法都是相同的,因此相同类型的对象共用成员方法。
那么问题来了,相同类型的对象共享成员方法,那么怎么知道是哪个对象调用这个成员方法。
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
class CGoods
{
public:
//void RegisterGoods(CGoods *this, char name[], int amount, float price)
void RegisterGoods(char name[], int amount, float price)
{
strcpy(Name, name); //相当于strcpy(this->Name, name);
Amount = amount; this->Amount = amount;
Price = price; this->Price = price;
}
int getamount(void)
{
return Amount;
}
private:
char Name[];
int Amount;
float Price;
};
int main(int argc, char **argv)
{
CGoods cd1,cd2;
//RegisterGoods(&cd1, "c++", 10, 20);
cd1.RegisterGoods("c++", 10, 20); 调用这个方法时会被改为//RegisterGoods(&cd1, "c++", 10, 20);
cd2.RegisterGoods("linux", 20, 100);
cout<<cd1.getamount()<<endl;
return 0;
}
例如这个例子怎么知道两个相同类型的对象cd1, cd2是哪个对象调用成员函数RedisterGoods()进行商品的注册?用的是this指针(可能有人会担心这个指针会不会被别人修改,不会被修改,因为这个this指针是被const修饰【CGoods *const this】)
上面很难理解那么看看下面这个c语言的例子有助于理解
struct CGoods{
char Name[];
int Amount;
float Price;
};
void RegisterGoods(CGoods *cgoods, char name[], int amount, float price)
{
strcpy(cgoods->Name, name); //如果把CGoods *cgoods换成CGoods *this不就和上面的一样了嘛,这个用法
cgoods->Amount = amount; //相当于c++里面的this指针
cgoods->Price = price;
}
int main(int argc, char **argv)
{
CGoods cd1, cd2;
RegisterGoods(&cd1, "c++", 10, 20);
RegisterGoods(&cd2, "linux", 20, 100);
return 0;
}