栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ this指针

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ this指针

偷偷拿来记录一下萌新的cs路——day 27 C++ this指针用法

#include 
using 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。代码如下:

#include 
using 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;
}

运行结果:

若不使用引用方式返回而采取值返回方式,代码如下:

#include 
using 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;
}

运行结果:

每次返回均是一个新对象,故不能产生累积的效果。

使用空指针时提高代码健壮性:

#include
using 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时结束,则提高了代码的健壮性。

以后学了新知识还会回来更新的!有误之处恳请大佬指正,提前感谢!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1011374.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号