this指针常用用法(C++ )
来源:互联网 发布:windows 登陆服务器 编辑:程序博客网 时间:2024/05/22 08:26
this指针的常用用法:
1、 成员函数调用中的this指针1)当一个成员函数被调用时,自动向它传递一个隐含的参数(this指针),该参数是一个指向这个成员函数所在的对象的指针。
2)当对一个对象调用成员函数时,编译程序先将对象的地址赋给this指针,然后调用成员函数.
3)每次成员函数存取数据成员时,由隐含使用this指针。
2、this指针的属性
this指针被隐含地声明为: X *const this,这意味着不能给this 指针赋值;
3、const成员函数中的this指针
在X类的const成员函数中,this指针的类型为:const X* const, 这说明this指针所指向的这种对象是不可修改的(即不能对这种对象的数据成员进行赋值操作);
4、 由于this并不是一个常规变量,所以,不能取得this的地址。
代码如下:
#include <stdio.h>#include <string.h>#include <system>class Person {public:typedef enum { BOY = 0, GIRL = 1,} SexType;public:Person(char *n, int a, SexType s)//成员获取,隐含使用T*const 类型的this指针{ name = new char[strlen(n)+1]; //这里的 name 等价于this->name strcpy(name,n); //这里的 name 等价于this->name age = a; //这里的 age 等价于this->age sex = s; //这里的 sex 等价于this->sex}int get_age(void) const//this指针的const属性{ //age++; //compile error, 因为 age等价于this->age,而 get_age又是一个const成员函数 ,则传入的指针是const T* const 类型的this指针 return age;}Person& add_age(int a)//链式引用{ age +=a; return *this; // 返回本对象的引用}void Person::assign(Person& p)//作为判断对象的基准{if(&p!=this) //要保证pointer不等于this{ X=pointer.X; Y=pointer.Y;}}private:char *name;int age;SexType sex;};void TestPerson(void){Person ZhangSan("ZhangSan", 20, Person::BOY);printf("ZhangSan.age = %d\n", ZhangSan.get_age());printf("ZhangSan.add_age = %d\n", ZhangSan.add_age(1).get_age()); //增加1岁的同时,可以对新的年龄直接输出;return;}int main(void){TestPerson();system("pause");}
/* result: ZhangSan.age = 20
ZhangSan.add_age = 21
*/
- this指针常用用法(C++ )
- C++this 指针用法详解
- C++this指针的用法
- this指针(C++)
- C++this指针的理解和用法
- C++this指针的理解和用法
- this指针说明(c++)
- C++(9):this指针
- 【C/C++】this指针
- this指针的用法
- this指针用法
- this指针的用法
- this指针用法
- this指针用法详解
- this指针的用法
- this指针的用法
- this指针用法
- this指针的用法
- 3.限制Linux对外联机的端口
- js控制select选定项问题
- scanf能不能与gets一起用
- 虚函数和纯虚函数的区别
- linux vi替换字符串
- this指针常用用法(C++ )
- Linux VPN服务器搭建
- BZOJ 1588 BZOJ 1503 平衡数splay
- Linux下如何搭建VPN服务器
- 向Web开发人员推荐12款优秀的 Twitter Bootstrap 组件和工具
- 三月其他零散知识(技术)
- 计算机是怎么启动起来的?值得一看
- 【Linux】Ubuntu 12.04和Windows 7双系统安装图解
- ServiceDescriptionImporter 类在 vs2010 无法引用的解决方法