C++:this指针
2015-10-26 17:37
471 查看
this指针
this关键字:表示本类中的对象成员,可以通过this指针访问当前类的成员
//举例
this关键字:表示本类中的对象成员,可以通过this指针访问当前类的成员
//举例
//例 3.18 隐藏this指针的引例 #include<iostream> using namespace std; class A{ public: A(int x1) { x = x1; } void dis() { cout<<"x = "<<x<<endl; } private: int x; }; int main() { A a(1),b(2); cout<<"a:"; a.dis(); cout<<"b:"; b.dis(); return 0; } /* 运行结果: a:x = 1 b:x = 1 @当this指针指向a时: cout<<"x = "<<x<<endl ----> cout<<"x = "<<this->x<<endl ---> cout<<"x = "<<a.x<<endl @成员函数:void dis() { cout<<"x = "<<x<<endl; } 实际使用时,C++编译系统把它处理为: void dis(*this) { cout<<"x = "<<this->x<<endl } 此时:调用a.dis()---->调用a.dis(&a),这样在进行函数调用时,编译系统就对象 a的地址传给形参this指针,成员函数执行后,输出了a.x的值。 */ //例3.19 显示this指针的值 #include<iostream> using namespace std; class A{ public: A(int x1) { x = x1; } void dis() { cout<<"this = "<<this<<" when x="<<this->x<<endl; } private: int x; }; int main() { A a(1),b(2),c(3); a.dis(); b.dis(); c.dis(); return 0; } 运行结果: this = 0012FF7C when x = 1 this = 0012FF78 when x = 2 this = 0012FF74 when x = 3
相关文章推荐
- C++:String类
- C++:对象指针
- C++学习笔记6 - 分支语句和逻辑运算符
- C++:对象数组
- 日志库EasyLogging++学习系列(4)—— 格式说明符
- typedef和struct结合
- CUDAExample-0-cppIntegration
- 最后一个单词的长度(LintCode)
- c++ 解析json
- 关于C语言中的连接符的用法 # ## macro stringize
- 第7周项目4 队列数组
- C++调用Python代码
- C++著名程序库的比较和学习经验
- 第7周项目3 负数把正数赶出队列
- 内存对齐的问题
- C++设计模式之桥接模式(改编自C++设计模式)
- 日志库EasyLogging++学习系列(3)—— 配置功能
- C/C++ 排序算法大全代码
- C++primer学习:重载运算(2)
- C++:概述