- 1.this指针
- 1.1this指针的特征
- 1.2经典题目
以日期类引出this指针
class date
{
public:
void print()
{
cout <<_year << "-" <<_month << "-" <<_day << endl;
}
void init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
date d1;
date d2;
date d3;
d1.init(2020, 5, 12);
d2.init(2022, 5, 10);
d1.print();
d2.print();
return 0;
}
在函数调用时,编译器是如何确定调用的对象?
C++中通过引入this指针:C++编译器给每个“非静态的成员函数”增加了一个隐藏的指针参数,让该指针指向当前的对象,在函数体中所有成员变量的操作,都通过该指针区访问。只不过该指针是编译器自动完成,不需要用户完成。
//上述程序相当于
class date
{
public:
void print()
{
cout << this << endl;
cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
}
void init(int year, int month, int day)
{
this->_year = year;
this->_month = month;
this->_day = day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
date d1;
date d2;
date d3;
d1.init(2020, 5, 12);
d2.init(2022, 5, 10);
d1.print();
cout << "d1:" << &d1 << endl;
d2.print();
cout << "d2:" << &d2 << endl;
return 0;
}
成员函数内部可以使用this指针
class date
{
public:
void print()
{
cout << this << endl;
cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
}
void init(int year, int month, int day)
{
this->_year = year;
this->_month = month;
this->_day = day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
date d1;
date d2;
date d3;
d1.init(2020, 5, 12);
d2.init(2022, 5, 10);
d1.print();
d2.print();
cout << "d1:" << &d1 << endl;
cout << "d2:" << &d2 << endl;
return 0;
}
1.1this指针的特征
1.2经典题目
- this指针类型:* const this
- 只能在成员函数内部使用
- this指针本质上其实是一个成员函数的形参。**对象中不存储this指针。**成员函数存放在公共代码区
- this指针是成员函数第一个隐含的指针形参,一般存放在虚拟进程地址空间中的栈区,在编译器优化的情况下存放在ecx寄存器中。
class A
{
public:
void print()
{
cout <<"print()" << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->print();
}
上述程序能否正常运行?
程序可以正常运行。成员函数存储在公共代码区,汇编语言中通过call的方式调用函数。所以p并没有解引用。
class A
{
public:
void print()
{
cout <<_a << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->print();
}
上述的程序直接运行崩溃,虚拟进程地址空间中00000000处的地址是专门用来初始指针,没有存储任何内容。



