C++ this指针 学习笔记

#include <iostream>

using namespace std;

class Person
{
public:
//    Person(int age)
//    {
//        age = age;
//    }
    //函数重载
    Person(int age,int flag)
    {
        if (flag)
        {
            //this指针指向 被调用的成员函数 所属的对象
            this->age = age;
        }
    }
    int age;

    void PersonAddAge(Person &p)
    {
        this->age += p.age;
    }
    //函数重载
    Person& PersonAddAge(Person &p, int flag)
    {
        if(flag)
        {
            this->age += p.age;
        }
        return *this;
    }
};

//void test01()
//{
//    Person P1(18);
//    cout << P1.age << endl;
//}

void test02()
{
    Person P2(19,1);
    cout << P2.age << endl;
}

void test03()
{
    Person P3(10,1);
    Person P4(10,1);
    P3.PersonAddAge(P3);
    //P3.PersonAddAge(P3).PersonAddAge(P3);//报错 因为返回值为void 不是对象
    cout << "P3的age:" << P3.age << endl;
}

void test04()
{
    Person P5(10,1);
    Person P6(10,1);
    P6.PersonAddAge(P5,1).PersonAddAge(P5,1).PersonAddAge(P5,1);
    //*this返回了对象本身 但在函数返回值的时候需要注明
    //Person类型为值类型 每次返回的对象都是拷贝构造函数复制的对象 打印出来仅有一次对该对象本身的操作
    //Person& 解引用类型才是返回对象本身
    cout << "P6的age:" << P6.age << endl;
}
int main()
{
    // this指针的用途
    // 1、当形参和成员变量同名时,可用this指针来区分
    // 2、this指针不需要定义 直接使用
    // 3、在类的非静态成员函数中返回对象本身 可以用 return *this   (返回本体)
    //test01();//返回的为Person::age的地址  证明赋值操作并不成功
    test02();// success
    test03();
    test04();
    cout << "Hello World!" << endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值