c++之this指针
来源:互联网 发布:seo网站关键词优化 编辑:程序博客网 时间:2024/05/18 01:34
内容转载于博客园 博客大牛秋水Leo
C++ this指针的用法
1. this 指针是一个隐含于每一个成员函数中的特殊指针。它指向正在被该成员函数操作的那个对象。 2. 当对一个对象调用成员函数时,编译程序先将对象的地址赋给this指针,然后调用成员函数,每次成员函数存取数据时,隐含使用this指针。 3. 当一个成员函数被调用时,自动向它传递一个隐含参数,该参数是一个指向这个成员函数所在的对象的指针。 4. 在C++中,this指针被隐含地声明为:X *const this,这意味着不能给this指针赋值。 5. 由于this不是一个常规常量,所以不能取得this的指针 6. 在以下场景中,经常需要显示引用this指针 (1)为实现对象的链式引用;(例1) (2)为避免对同一对象赋值操作;(例2) (3)在实现一些数据结构时,如list
#include <stdio.h>#include <string.h>class Person { public: typedef enum { BOY = 0, GIRL = !BOY } SexType; public: Person(char *n, int a, SexType s) { 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 { //age++; //compile error, 因为 age等价于this->age,而 get_age又是一个const成员函数, //不能对 this指针所指向的这种对象进行修改,这也是const的一个作用。 //这样做的好处是,增加了代码的健壮性。 return age; } Person& add_age(int a) { age +=a; return *this; // 返回本对象的引用 } 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(); while(1);}/* result: ZhangSan.age = 20 ZhangSan.add_age = 21*/
#include <stdio.h>class Location { int X,Y;//默认为私有的 public: void init(int x,int y) { X =x; Y = y;}; void assign(Location& pointer); int GetX(){ return X; } int GetY(){ return Y; }};void Location::assign(Location& pointer){ if(&pointer!=this) //同一对象之间的赋值没有意义,所以要保证pointer不等于this { X=pointer.X; Y=pointer.Y; }}int main(){ Location x; x.init(5,4); Location y; y.assign(x); printf("x.X = %d, x.Y = %d \n", x.GetX(), x.GetY()); printf("y.X = %d, y.Y = %d ", y.GetX(), y.GetY()); while(1); return 0;}/* result: x.X = 5, x.Y = 4 y.X = 5, y.Y = 4 */
阅读全文
0 0
- 【C++】:C++之this指针的作用
- 【C/C++】this指针
- C++this指针、智能指针
- 【C++】this 指针
- C++this指针
- C++this指针
- C++this指针
- C++this指针
- C++this指针
- c++this指针
- C++this指针
- C++this指针
- C++this指针(二)
- C++-this指针
- c++this指针
- C++this指针
- C ++的this指针
- C++this指针详解
- ubuntu 14.04 交叉编译器的制作工具以及制作教程
- HDU题目分类
- redis事务浅析
- Java直接插入排序
- 6. ZigZag Conversion leetcode
- c++之this指针
- 二叉树的高度 、销毁、链表的翻转(k为一组、n-m 之间)两种实现、
- 函数的属性和方法
- MySQL数据库命令行详解
- Android实战中与Json数据、Java-Bean相关的效率技巧
- 文件归档及传输
- Python爬虫框架Scrapy学习一记——认识Scrapy
- 考研数据结构----MaxHeap
- Java面试题温习