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语言指针++