偷偷拿来记录一下萌新的cs路——day 27 C++ this指针用法
#includeusing namespace std; class Person { public: Person(int age) { this->age = age; // this指针指向被调用的成员函数所属对象(p1) } void PernsonAddAge(Person& p) { this->age += p.age; } int age; }; // 解决名称冲突 void test01() { Person p1(18); cout << "age of p1: " << p1.age << endl; } // *this 返回对象本身 void test02() { Person p1(10); Person p2(10); p2.PernsonAddAge(p1); // p1年龄加至p2 cout << "age of p2: " << p2.age << endl; } int main() { test01(); test02(); return 0; }
运行结果
若在test02中要不断将p1年龄加至p2,则PersonAddAge需返回p2。由于this是指向p2的指针,*this是p2本体,故可返回*this。代码如下:
#includeusing namespace std; class Person { public: Person(int age) { this->age = age; // this指针指向被调用的成员函数所属对象(p1) } Person& PernsonAddAge(Person& p) { // 引用方式作返回 this->age += p.age; return *this; } int age; }; // *this 返回对象本身 void test02() { Person p1(10); Person p2(10); p2.PernsonAddAge(p1).PernsonAddAge(p1).PernsonAddAge(p1).PernsonAddAge(p1); // p1年龄四次加至p2 cout << "age of p2: " << p2.age << endl; } int main() { test02(); return 0; }
运行结果:
若不使用引用方式返回而采取值返回方式,代码如下:
#includeusing namespace std; class Person { public: Person(int age) { this->age = age; // this指针指向被调用的成员函数所属对象(p1) } Person PernsonAddAge(Person& p) { // 值返回 this->age += p.age; return *this; } int age; }; // *this 返回对象本身 void test02() { Person p1(10); Person p2(10); p2.PernsonAddAge(p1).PernsonAddAge(p1).PernsonAddAge(p1).PernsonAddAge(p1); // p1年龄加至p2 cout << "age of p2: " << p2.age << endl; } int main() { test02(); return 0; }
运行结果:
每次返回均是一个新对象,故不能产生累积的效果。
使用空指针时提高代码健壮性:
#includeusing namespace std; class Person { public: void showClassName() { cout << "This is Person class" << endl; } void showPersonAge() { if (this == NULL) return; // 提高代码健壮性 cout << "age = " << m_Age << endl; // m_Age = this-> m_Age } int m_Age; }; void test01() { Person* p = NULL; p->showClassName(); p->showPersonAge(); } int main() { test01(); return 0; }
由于类中m_Age实际上是this->m_Age,所以当test01中初始化指针后,p->showPersonAge行会报错。若加上判断,this==NULL时结束,则提高了代码的健壮性。
以后学了新知识还会回来更新的!有误之处恳请大佬指正,提前感谢!



