C++之全局函数和成员函数的转换

全局函数和成员函数

  • 把全局函数转化成成员函数,通过this指针隐藏左操作数
 Test add(Test &t1, Test &t2)===》Test add(Test &t2)
  • 把成员函数转换成全局函数,多了一个参数
void printAB()===》void printAB(Test *pthis)
  • 函数返回元素和返回引用

                Test& add(Test &t2) //*this //函数返回引用
                {
                      this->a = this->a + t2.getA();
                      this->b = this->b + t2.getB();
                      return *this; //*操作让this指针回到元素状态
                } 

                Test add2(Test &t2) //*this //函数返回元素
                {
                      //t3是局部变量
                      Test t3(this->a+t2.getA(), this->b + t2.getB()) ;
                      return t3;
                }

重要函数展示:

#include <stdio.h>

class Test1_1
{
public:
    Test1_1 (int a)
    {
        this->a = a;
    }

    void print()
    {
        printf ("a = %d\n", a);
    }

    // 将全局函数改成内部函数可以通过 this 隐藏左操作数
    int add(Test1_1 &b)  //===> add(Test1_1 *const this, Test1_1 &b)
    {
        return this->a+b.GetA();
    }

    int GetA()
    {
        return a;
    }
private:
    int a;
};


int GetA(Test1_1 &obj)
{
    return obj.GetA();
}

// 全局函数
int add(Test1_1 &a, Test1_1 &b)
{
    return a.GetA()+b.GetA();
}

int main1_1()
{
    Test1_1 a(10), b(20);

    // int c = add(a, b);
     int c = a.add(b);    // a+b        b.add(a) ===>  b+a

    printf ("c = %d\n",c);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值