c语言指针++_C ++此指针| 查找输出程序| 套装3

c语言指针++

Program 1:

程序1:

#include <iostream>
using namespace std;

class Test {
    int VAL;

public:
    Test(int v)
    {
        VAL = v;
    }
    Test* Sum(Test T1, Test T2)
    {
        VAL = T1.VAL + T2.VAL;

        return this;
    }
    void print()
    {
        cout << VAL << " ";
    }
};

int main()
{
    Test T1(10);
    Test T2(20);

    Test* T3;

    T3 = T1.Sum(T1, T2);

    T1.print();
    T2.print();
    T3->print();

    return 0;
}

Output:

输出:

30 20 30

Explanation:

说明:

Consider the sum() function, the function is taking two objects of Test class arguments and returning the pointer of the current object using this

考虑sum()函数,该函数接收Test类参数的两个对象,并使用this返回当前对象的指针。

And, in the main() function, we created two objects T1, T2, and a pointer T3, which is holding the current object pointer returned by sum(). The sum() is adding the values of T1 and T2 and assigning in T1 because we are calling the function sum() using T1 and returning the address of T1 which is assigning to the pointer T3.

并且,在main()函数中,我们创建了两个对象T1T2和一个指针T3 ,该指针保存了sum()返回的当前对象指针。 sum()T1T2的值相加并在T1中赋值,因为我们正在使用T1调用函数sum()并返回分配给指针T3T1地址。

Program 2:

程式2:

#include <iostream>
using namespace std;

class Test {
public:
    Test call1()
    {
        cout << "call1 ";
        return *this;
    }
    Test call2()
    {
        cout << "call2 ";
        return *this;
    }
    Test call3()
    {
        cout << "call3 ";
        return *this;
    }
};

int main()
{
    Test T1;

    T1.call1().call2().call3();

    return 0;
}

Output:

输出:

call1 call2 call3

Explanation:

说明:

Here, we implemented a cascaded function call using this pointer, and created the class Test with 3 member functions call1(), call2(), and call3(). All these functions will return the current object of the class using *this.

在这里,我们使用此指针实现了级联函数调用,并使用3个成员函数 call1()call2()call3()创建了Test类。 所有这些函数都将使用* this返回类的当前对象。

翻译自: https://www.includehelp.com/cpp-tutorial/this-pointer-find-output-programs-set-3.aspx

c语言指针++

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值