C++函数探幽——this指针(还不懂this指针?看完包废的)
类中只存储成员变量,不会存储成员函数类中不存储成员函数,而同一个类创建的多个对象在调用同一个函数时,它们是怎么区分的呢?
目录
引入
对于一个类来说,它可以创建出很多个对象,而我们知道在类中只存储成员变量,不会存储成员函数
大家是否有过一个疑问:类中不存储成员函数,而同一个类创建的多个对象在调用同一个函数时,它们是怎么区分的呢?
比如:
class Date
{
public:
//默认构造
Date(int y = 1, int m = 1, int d = 1)
{
year = y;
month = m;
day = d;
}
//成员函数
void print()
{
cout << year << " " << month << " " << day << endl;
}
private:
int year;
int month;
int day;
};
int main()
{
Date d1;
Date d2;
Date d3;
d1.print();
d2.print();
d3.print();
}

因此这里我们就要了解使用C++中的【this】指针了
一、【this】指针
我们通过对象来调用成员函数时,那么这个函数操作的就是这个对象中的数据,因此:
编译器在调用成员函数时将【this】作为隐藏的参数传递给了成员函数,而【this】指针指向调用成员函数的对象
我们实际在通过对象来调用成员函数时成员函数的实参和形参都会比实际的个数多出一个【this】指针
实际的函数调用:
int main()
{
Date d1;
Date d2;
Date d3;
//实际参数列表
//d1.print(&d1);
d1.print();
//实际参数列表
//d2.print(&d2);
d2.print();
//实际参数列表
//d3.print(&d3);
d3.print();
}
实际的成员函数:
//实际的成员函
//void print(Date* const this)
void print()
{
cout << this->year << " " << this->month << " " << this->day << endl;
}
调试窗口:

可以观察到虽然我们没有传递任何参数,但是编译器将【this】作为隐藏的参数传递给了成员函数,而【this】指针指向调用成员函数的对象
二、【this】指针的特性
- 【this】指针不可以修改指向
- 【this】指针不可以在实参和形参的位置显示
- 【this】指针可以在类中显示的使用
1、【this】指针不可以修改指向
class Test
{
public:
Test(int n = 1)
{
num = n;
}
void test()
{
Test tmp(2);
this = &tmp;
}
private:
int num;
};

2、【this】指针不可以在实参和形参的位置显示
形参的位置显示:
class Test
{
public:
Test(int n = 1)
{
num = n;
}
//形参的位置显示
void test(Test* const this)
{
this->num = 100;
}
private:
int num;
};

实参的位置显示 :
int main()
{
Test t1;
//实参的位置显示
test(&t1);
return 0;
}

3、【this】指针可以在类中显示的使用
在成员函数中访问调用成员函数的对象的数据时,编译器默认的会把【this】指针加上,因此我们加上【this】指针和不加上【this】指针都是可以的
后续的运算符重载时会显示的使用【this】指针
class Test
{
public:
Test(int n = 1)
{
num = n;
}
void test()
{
//编译器默认的会把【this】指针加上
//我们加上【this】指针和不加上【this】指针都是可以的
this->num = 100;
num = 200;
cout << num << endl;
}
private:
int num;
};
三、【const】成员函数
将【const】修饰的成员函数称之为【const】成员函数,【const】修饰成员函数放到成员函数参数列表的后面,比如:
class Test
{
public:
Test(int n = 1)
{
num = n;
}
//【const】成员函数
void print()const
{
cout << num << endl;
}
private:
int num;
};
【const】实际修饰该成员函数隐含的【this】指针,表明在该成员函数中不能对类的任何成员进⾏修改
看一下以下代码:
class Test
{
public:
Test(int n = 1)
{
num = n;
}
void print()
{
cout << num << endl;
}
private:
int num;
};
int main()
{
const Test t1;
t1.print();
return 0;
}

这是一个很经典的权限放大问题,编译器隐式传递的【this】指针默认是可以修改的,而函数调用实际传递的参数是不可以修改的
正是因为这一方面的缺陷将【const】放到成员函数参数列表的后面,【const】将修饰该成员函数隐含的【this】指针,让其达到权限平移
class Test
{
public:
Test(int n = 1)
{
num = n;
}
void print() const
{
cout << num << endl;
}
private:
int num;
};
int main()
{
const Test t1;
//权限平移
t1.print();
return 0;
}

建议:
所有不修改成员变量的成员函数都建议加上【const】
更多推荐
所有评论(0)