author:&Carlton
tag:C++
topic:【C++】this指针及其用途、空指针访问成员函数、常函数常对象
website:黑马程序员C++
date:2023年7月19日
目录
this指针及其用途
this指针是隐含在成员函数的指针,指向被调用函数所属的对象。
常用于以下两个用途:
①解决参数与成员变量名字冲突。
②返回对象本身。
空指针访问成员函数
空指针可以访问成员函数但不能使用成员变量,访问的成员函数也不应有对成员属性有相关操作。
常函数常对象
常函数不能更改成员属性的值,因为this指针本质是指针常量,再加上const修饰后不仅指向关系不能更改,指向对象的属性值也不能改变。
常对象只能使用常函数。
mutable修饰的属性除外。
实例:
三个测试函数分别对应三个专题。
每个文件都有各自的作用,分开清晰,文件有注释,附上了必要、实用的解释。
头文件
1.Person.h
#pragma once
#include <iostream>
using namespace std;
class Person
{
public:
int m_age, age;//对于参数与成员变量名字冲突问题,可以使用m_age(member_age)避免,或者使用this指针解决
Person(int age);
Person& PersonAddAge(Person p);
void PersonAge();
};
2.Class.h
#pragma once
#include <iostream>
using namespace std;
class Class
{
public:
//成员属性
mutable int special;//可以在常函数中改变其值
int number;
void PersonClassName();
void ClassNumber();
void Const()const;
};
3.test.h
#pragma once
#include <iostream>
#include "Class.h"
#include "Person.h"
using namespace std;
void test01();
void test02();
void test03();
源文件
1.main.cpp
#include <iostream>
#include "Person.h"
#include "Class.h"
#include "test.h"
using namespace std;
int main()
{
test01();
test02();
test03();
return 0;
}
2.test.cpp
#include "test.h"
void test01()//this指针的用途专题测试函数
{
Person p1(10);
Person p2(10);
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);//链式编程思想
cout << "p2的年龄是: " << p2.age << endl;
}
void test02()//空指针访问成员函数专题测试函数
{
Class* p = NULL;//定义一个指向Class类对象的空指针p
//通过空指针访问成员函数PersonClassName 和 ClassNumber
p->PersonClassName();
p->ClassNumber();
//存在问题,因为空指针若访问成员函数不能涉及成员变量,空指针指向的类对象里没有实例化的成员变量,在该函数内部应设计及时检测NULL并退出
}
void test03()//常函数和常对象专题测试函数
{
Class const p;
p.Const();
cout << p.special << endl;
//p.PersonClassName();
//常对象只能调用常函数
}
3.this指针的用途.cpp
#include "Person.h"
Person::Person(int age)//Person的有参构造函数
{
this->age = age;//this指向被调用的成员函数所属对象
}
Person& Person::PersonAddAge(Person p)
{
this->age += p.age;
return *this;//返回该对象本身,用于此情况时返回值是引用的,重复作用该对象本身,否则是浅拷贝该对象数值,新建另外一个对象
}
void Person::PersonAge()
{
m_age = 10;
}
4.空指针访问成员函数.cpp
#include "Class.h"
void Class::PersonClassName()//没有涉及成员变量
{
cout << "This is PersonClassName" << endl;
}
void Class::ClassNumber()//涉及更改成员变量
{
if (this == NULL)
{
return;//若检测到传入的是空指针,退出函数提高程序健壮性
}
number = 10;
}
5.常函数和常对象.cpp
#include "Class.h"
void Class::Const() const//常函数,函数内部不可以修改成员属性
{
//number = 10;
//成员属性加了关键字mutable可以在常函数里修改其值,否则不可以
special = 100;
}
/*
原因在于this指针的本质:this指针是一个指针常量,其指向不可更改,仅指向被调用函数所属对象,则number = 10实际等效于this->number = 10,
而在const修饰的常函数中,意味着const *Person const this,不仅其指向不可更改,其指向的对象的值也不可以修改,
*/
欢迎指正与分享,谢谢!