C++类和对象: this指针

 

1. this指针的概念与特性

this指针概念

首先来看一个例子

#include <iostream>
using namespace std;
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
int main()
{
Date d1, d2;
d1.Init(2022, 1, 11);
d2.Init(2023, 4, 28);
d1.Print();
d2.Print();
}

d1和d2调用的是相同的成员函数, 因为成员函数Print是存储在公用代码段而不是对象中

那么, 为什么它们最后打印的结果不同 ?

实际上d1和d2在调用成员函数Print时, 向Print函数隐含传递了对象的地址, Print成员函数会有一个名为this指针的形参来接收, 最后通过this指针打印

下面具体看一下编译器做了什么

#include <iostream>
using namespace std;
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print() // 3. void Print(Date* this)
{
cout << _year << "-" << _month << "-" << _day << endl;
// 4. cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
int main()
{
Date d1, d2;
d1.Init(2022, 1, 11);
d2.Init(2023, 4, 28);
d1.Print();
// 1. d1.Print(&d1); 传递对象d1的地址
d2.Print();
// 2. d2.print(&d2); 传递对象d2的地址
}

1. 对象d1,d2在调用成员函数时都会隐式的传递各自对象的地址

2. Print成员函数根据类创建this指针 

3. 使用this指针调用其对象中的成员变量

所以因为this指针的存在, 最后打印出的结果不同, 这些东西都是编译器自动生成的, 是为了方便使用

this指针的特性

this指针不能在形参和实参显示传递

但是可以在函数内部显示使用

2. this指针的练习

// 1.下面程序编译运行结果是? A、编译报错 B、运行崩溃 C、正常运行
class A
{
public:
void Print() // void Print(A* this)
{
cout << "Print()" << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->Print(); // Print(p)
return 0;
}

因为Print成员变量是存储在公用代码段中, 所以Print可以正常调用

然后, 对象调用成员函数都会隐式的传递其对象的地址, p->Print()  -------》  Print(p), 也就是传递一个空指针

最后,因为只有访问(解引用)空指针才会报错, 这里只是打印没有解引用空指针, 所以正常运行

// 2.下面程序编译运行结果是? A、编译报错 B、运行崩溃 C、正常运行
class A
{
public:
void PrintA() // void PrintA(A* this)
{
cout<<_a<<endl; // cout<< this->_a <<endl; 解引用空指针, 所以运行崩溃
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->PrintA(); // 调用PrintA(p)
return 0;
}

这道题与之前类似, 但是因为访问了空指针this, 所以运行崩溃 

注意: 编译报错是语法错误,这里不是

posted @   许木101  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示