我是靠谱客的博主 单身小熊猫,这篇文章主要介绍this指针1.this指针定义2.举例,现在分享给大家,希望可以做个参考。

1.this指针定义

在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。this 指针是所有成员函数的隐含参数。因此,在成员函数内部,它可以用来指向调用对象。友元函数没有 this 指针,因为友元不是类的成员。只有成员函数才有 this 指针。

2.举例

比较两个成员的大小

1)普通函数

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream> using namespace std; class Box { private: int Lenght{ 1 }; int width{ 1 }; int height{ 1 }; public: explicit Box(int x, int y, int z):Lenght { x }, width { y }, height { z }{} //构造函数 int volume() { return Lenght * width * height; } }; bool compare(Box box11, Box box22) { return box11.volume()< box22.volume(); } int main() { Box box1{ 5,5,5 }; Box box2{ 5,5,10 }; cout << box1.volume() << endl;//结果125 cout << compare(box1,box2) << endl; //结果1 return 0; }

2)this指针

   通过this 指针在类中访问当前对象的成员

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream> using namespace std; class Box { private: int Lenght{ 1 }; int width{ 1 }; int height{ 1 }; public: explicit Box(int x, int y, int z):Lenght { x }, width { y }, height { z }{} //三形参的构造函数 int volume() { return Lenght * width * height; } bool compare(Box box22) { return this -> volume() < box22.volume(); } }; int main() { Box box1{ 5,5,5 }; Box box2{ 5,5,10 }; cout << box1.volume() << endl;//结果5 cout << box1.compare(box2) << endl; //结果1 //cout << box2.getheight(box1) << endl; return 0; }

最后

以上就是单身小熊猫最近收集整理的关于this指针1.this指针定义2.举例的全部内容,更多相关this指针1内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(66)

评论列表共有 0 条评论

立即
投稿
返回
顶部