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語言指針++