C++读书笔记之this指针的用法

C++ this指针的用法

this指针的含义及其用法:
1.  this指针是一个隐含于每一个成员函数中的特殊指针。
    它指向正在被该成员函数操作的那个对象。
2.  当对一个对象调用成员函数时,编译程序先将对象的地址赋给this指针,
    然后调用成员函数,每次成员函数存取数据成员时,由隐含使用this指针。
3.  当一个成员函数被调用时,自动向它传递一个隐含的参数,
    该参数是一个指向这个成员函数所在的对象的指针。
4.  在C++中,this指针被隐含地声明为: X *const this,这意味着不能给this 指针赋值;
    在X类的const成员函数中,this指针的类型为:const X* const,
    这说明this指针所指向的这种对象是不可修改的(即不能对这种对象的数据成员进行   赋值操作);
5.  由于this并不是一个常规变量,所以,不能取得this的地址。
6.  在以下场景中,经常需要显式引用this指针
    (1) 为实现对象的链式引用(如例Person);
    (2) 为避免对同一对象进行赋值操作(如例Location);

    (3) 在实现一些数据结构时,如list.


The keyword this identifies a special type of pointer. Suppose that you create an object namedx of class A, and class A has a nonstatic member function f(). If you call the functionx.f(), the keyword this in the body of f() storesthe address of x. You cannot declare the this pointeror make assignments to it.

A static member function does not have a this pointer.

The type of the this pointer for a member function of a classtypeX, is X* const. If the member function is declared with theconst qualifier, the type of the this pointer for that member function for classX, is constX* const.

A const this pointer can by used only with const member functions. Data members of the class will be constant within that function.

The this pointer is passed as a hidden argument to all nonstaticmember function calls and is available as a local variable within the bodyof all nonstatic functions.

For example, you can refer to the particular class object that a memberfunction is called for by using thethis pointer in the body ofthe member function. The following code example produces the outputa = 5:

#include <iostream>
using namespace std;

struct X {
private:
  int a;
public:
  void Set_a(int a) {

    // The 'this' pointer is used to retrieve 'xobj.a'
    // hidden by the automatic variable 'a'
    this->a = a;
  }
   void Print_a() { cout << "a = " << a << endl; }
};

int main() {
  X xobj;
  int a = 5;
  xobj.Set_a(a);
  xobj.Print_a();
}

In the member function Set_a(), the statement this->a =a uses the this pointer to retrieve xobj.a hiddenby the automatic variable a.

Unless a class member name is hidden, using the class member name is equivalent to using the class member name with thethis pointer and the classmember access operator (->).


this Pointer


The this pointer is a pointer accessible only within the nonstatic member functions of aclass, struct, or union type. It points to the object for which the member function is called. Static member functions do not have athis pointer.

this 
this->member-identifier
Remarks

An object's this pointer is not part of the object itself; it is not reflected in the result of asizeof statement on the object. Instead, when a nonstatic member function is called for an object, the address of the object is passed by the compiler as a hidden argument to the function. For example, the following function call:
myDate.setMonth( 3 );

can be interpreted this way:

setMonth( &myDate, 3 );

The object's address is available from within the member function as the this pointer. Most uses of this are implicit. It is legal, though unnecessary, to explicitly usethis when referring to members of the class. For example:

void Date::setMonth( int mn )
{
   month = mn;            // These three statements
   this->month = mn;      // are equivalent
   (*this).month = mn;
}

The expression *this is commonly used to return the current object from a member function:

return *this;

The this pointer is also used to guard against self-reference:

if (&Object != this) {
// do not execute in cases of self-reference
NoteNote

Because the this pointer is nonmodifiable, assignments to this are not allowed. Earlier implementations of C++ allowed assignments tothis.

Occasionally, the this pointer is used directly — for example, to manipulate self-referential data structures, where the address of the current object is required.

#include <iostream>
#include <string.h>

using namespace std;

class Buf 
{
public:
    Buf( char* szBuffer, size_t sizeOfBuffer );
    Buf& operator=( const Buf & );
    void Display() { cout << buffer << endl; }

private:
    char*   buffer;
    size_t  sizeOfBuffer;
};

Buf::Buf( char* szBuffer, size_t sizeOfBuffer )
{
    sizeOfBuffer++; // account for a NULL terminator

    buffer = new char[ sizeOfBuffer ];
    if (buffer)
    {
        strcpy_s( buffer, sizeOfBuffer, szBuffer );
        sizeOfBuffer = sizeOfBuffer;
    }
}

Buf& Buf::operator=( const Buf &otherbuf ) 
{
    if( &otherbuf != this ) 
    {
        if (buffer)
            delete [] buffer;

        sizeOfBuffer =  strlen( otherbuf.buffer ) + 1; 
        buffer = new char[sizeOfBuffer];
        strcpy_s( buffer, sizeOfBuffer, otherbuf.buffer );
    }
    return *this;
}

int main()
{
    Buf myBuf( "my buffer", 10 );
    Buf yourBuf( "your buffer", 12 );

    // Display 'my buffer'
    myBuf.Display();

    // assignment opperator
    myBuf = yourBuf;

    // Display 'your buffer'
    myBuf.Display();
}
Output
my buffer
your buffer



/**********************************
C++ this指针的用法

this指针的含义及其用法:
1.  this指针是一个隐含于每一个成员函数中的特殊指针。
    它指向正在被该成员函数操作的那个对象。
2.  当对一个对象调用成员函数时,编译程序先将对象的地址赋给this指针,
    然后调用成员函数,每次成员函数存取数据成员时,由隐含使用this指针。
3.  当一个成员函数被调用时,自动向它传递一个隐含的参数,
    该参数是一个指向这个成员函数所在的对象的指针。
4.  在C++中,this指针被隐含地声明为: X *const this,这意味着不能给this 指针赋值;
    在X类的const成员函数中,this指针的类型为:const X* const,
    这说明this指针所指向的这种对象是不可修改的(即不能对这种对象的数据成员进行赋值操作);
5.  由于this并不是一个常规变量,所以,不能取得this的地址。
6.  在以下场景中,经常需要显式引用this指针
    (1) 为实现对象的链式引用(如例Person);
    (2) 为避免对同一对象进行赋值操作(如例Location);
    (3) 在实现一些数据结构时,如list.
***********************************/
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;

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 UESTC("UESTC", 2013-1956, Person::BOY);
    cout<<"UESTC.age = "<<UESTC.get_age()<<endl;
    cout<<"UESTC.add_age ="<<UESTC.add_age(1).get_age()<<endl;
}
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;
    }
}
void Test_location()
{
    Location x;
    x.init(5,4);

    Location y;
    y.assign(x);

    cout<<"x.X = "<<x.GetX()<<"  x.Y = "<<x.GetY()<<endl;
    cout<<"y.X = "<<y.GetX()<<"  y.Y = "<<y.GetY()<<endl;
}
int main(void)
{
    cout<<"-----TestPerson()------\n";
    TestPerson();
    cout<<"-----TestLocation()------\n";
    Test_location();
}
/****************************
running result:
-----TestPerson()------
UESTC.age = 57
UESTC.add_age =58
-----TestLocation()------
x.X = 5  x.Y = 4
y.X = 5  y.Y = 4

Process returned 0 (0x0)   execution time : 0.031 s
Press any key to continue.
******************************/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值