c++学习_this指针

    创建的每个对象里面既有数据成员,也有成员方法。但是我们知道相同类型的对象的成员方法都是相同的,因此相同类型的对象共用成员方法。

那么问题来了,相同类型的对象共享成员方法,那么怎么知道是哪个对象调用这个成员方法。

#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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值