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

c语言指针++

Program 1:

程序1:

#include <iostream>
using namespace std;

int main()
{
    int A = 10;
    this* ptr;

    ptr = &A;

    *ptr = 0;

    cout << *ptr << endl;

    return 0;
}

Output:

输出:

main.cpp: In function ‘int main()’:
main.cpp:7:5: error: invalid use of ‘this’ in non-member function
     this* ptr;
     ^~~~
main.cpp:7:11: error: ‘ptr’ was not declared in this scope
     this* ptr;
           ^~~

Explanation:

说明:

The code will generate an error because we cannot use this pointer outside the class. because this pointer points to the current object inside the class.

该代码将产生错误,因为我们不能在类外部使用此指针 。 因为指针指向类内的当前对象。

Program 2:

程式2:

#include <iostream>
using namespace std;

class Test {
    int T1;

public:
    Test()
    {
        this* ptr;

        *ptr = &T1;

        cout << *ptr;
    }
};

int main()
{
    Test T;

    return 0;
}

Output:

输出:

main.cpp: In constructor ‘Test::Test()’:
main.cpp:10:15: error: ‘ptr’ was not declared in this scope
         this* ptr;
               ^~~

Explanation:

说明:

The above code will generate an error because this is the default pointer of the current object we can access members of the class inside the class. But we cannot create pointers using this.

上面的代码将产生一个错误,因为是当前对象的默认指针,我们可以在该类内部访问该类的成员。 但是我们不能使用this创建指针。

In the above program, we created pointers using this inside the constructor, which is not correct.

在上面的程序中,我们在构造函数内部使用指针创建了指针,这是不正确的。

Program 3:

程式3:

#include <iostream>
using namespace std;

class Test {
    int T1;

public:
    Test()
    {
        T1 = 10;
        cout << this->T1;
    }
};

int main()
{
    Test T;

    return 0;
}

Output:

输出:

10

Explanation:

说明:

Here, we created a class Test that contains data member T1 and we defined a default constructor inside the class Test.

在这里,我们创建了一个包含数据成员 T1的 Test类,并且在Test类中定义了一个默认构造函数

In the constructor, we assign value 10 to the T1 and print using the below statement.

在构造函数中,我们将值10分配给T1并使用以下语句进行打印。

cout<<this->T1;

In the above statement, we accessed T1 using this, because the this is a pointer to the current object. Thus, it will print 10 on the console screen.

在上面的语句中,我们使用this来访问T1 ,因为this是指向当前对象的指针。 因此,它将在控制台屏幕上打印10。

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

c语言指针++

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值