1. this 指针引入
this指针 表示成员函数实际调用时,对象在内存中的位置
//basic.cpp
#include <iostream>
using namespace std;
class HeyBaby{
public:
HeyBaby(int x, int y) : cute_score (x), nauty_score(y){
cout << "constructor this& = " << this << endl;
}
void baby_show()
{
cout << "cute score = " << cute_score << " nauty score = " << nauty_score << endl;
cout << "this& = " << this << endl;
}
int cute_score;
int nauty_score;
};
int main (void)
{
HeyBaby Baby(100,99);
Baby.baby_show();
cout << "Baby address = " << &Baby << endl;
return 0;
}
输出:
constructor this& = 0x7fff63e4fe10
cute score = 100 nauty score = 99
this& = 0x7fff63e4fe10
Baby address = 0x7fff63e4fe10
2. this指针常量属性, this指针带有常属性和不带有常属性形成重载
#include <iostream>
using namespace std;
class HeyBaby{
public:
HeyBaby(int x, int y) : cute_score (x), nauty_score(y){
cout << "constructor this& = " << this << endl;
}
void baby_change (void) const {
//cute_score++; 这样写编译器会报错
cout << "this function could not change the member of this class" << endl;
}
void baby_change (void) {
cute_score++;
cout << "this function could change the member of this class" << endl;
}
int cute_score;
int nauty_score;
};
int main (void)
{
HeyBaby Baby_boy(100,99);
Baby_boy.baby_change();
HeyBaby const Baby_girl (100, 100);
Baby_girl.baby_change();
return 0;
}
constructor this& = 0x7ffe867b66d0
this function could change the member of this class
constructor this& = 0x7ffe867b66e0
this function could not change the member of this class