C++this指標
阿新 • • 發佈:2021-02-16
技術標籤:C++面向物件
this指標的用途:
this指標式C++的特殊的物件指標,可以用來區分哪個物件呼叫的相應的程式碼。
所以this指標指向被呼叫的成員函式所屬物件。
誰呼叫this就指向誰
this指標是隱含每個非靜態成員函式內的一種指標
this指標不需要定義,直接使用即可
this指標的用途:
當形參和成員變數同名時,可以用this指標來區分
在類的非靜態成員函式中返回物件本身,可用returnthis
(this是個指標,指向物件,如果加個則表示這個物件)
//1.解決名稱衝突
#include<iostream>
#include<string>
using namespace std;
class Person {
public:
int age;
Person(int age) {
age = age;
}
};
void test01() {
Person p(18);
cout << "P1的年齡為" << p.age << endl;
}
int main() {
test01();
return 0;
}
用上this指標之後
所以加了this之後就可以看出區別了,this指向這個屬性的成員變數,和此函式的形參區分開來
#include<iostream>
#include<string>
using namespace std;
class Person {
public:
int age;
Person(int age) {
this->age = age;
}
void ADD(Person &P) {
this->age += P.age;
}
};
//1.解決名稱的衝突
void test01() {
Person p(18);
cout << "P1的年齡為" << p.age << endl;
}
//2.返回物件本身用*this
void test02() {
Person p1(10);
Person p2(20);
p2.ADD(p1);
cout << "p2的年齡為:" << p2.age << endl;
}
int main() {
test02();
return 0;
}
如果想要多加幾次
那就需要用到this指標了
#include<iostream>
#include<string>
using namespace std;
class Person {
public:
int age;
Person(int age) {
this->age = age;
}
Person& ADD(Person &P) {//因為要返回物件本身,所以要來一個物件的引用
//如果返回值的話,則返回的是一個拷貝的新物件,和p2不一樣了,所以結果是不一樣的
this->age += P.age;
return *this;//返回物件的本體
}
};
//1.解決名稱的衝突
void test01() {
Person p(18);
cout << "P1的年齡為" << p.age << endl;
}
//2.返回物件本身用*this
void test02() {
Person p1(10);
Person p2(20);
//鏈式程式設計思想
p2.ADD(p1).ADD(p1).ADD(p1);
cout << "p2的年齡為:" << p2.age << endl;
}
int main() {
test02();
return 0;
}