zoukankan      html  css  js  c++  java
  • this指针

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

    友元函数是没有this指针的,因为友元不是类的成员,只有成员函数才有this指针。

    /***
    this.cpp
    ***/
    #include<iostream>
    using namespace std;
    
    class Box
    {
        public:
            Box(double l = 2.0,double b = 2.0,double h = 2.0)
            {
                cout << "Construct called." << endl;
                length = l;
                breadth = b;
                height = h;
            }
            double Volume()
            {
                return length*breadth*height;
            }
            int compare(Box box)
            {
                return this->Volume() > box.Volume();
            }
        private:
            double length;
            double breadth;
            double height;
    };
    
    int main()
    {
        Box box1(3.3,1.2,1.5);
        Box box2(8.5,6.0,2.0);
    
        if(box1.compare(box2))
        {
            cout<< "box2 is smaller than box1" << endl;
        }
        else
        {
            cout << "box2 is equal to or larger than box1" << endl; 
        }
        return 0;
    }

    运行结果:

    exbot@ubuntu:~/wangqinghe/C++/20190807$ ./this

    Construct called.

    Construct called.

    box2 is equal to or larger than box1

    引用this:

    当我们调用成员函数时,实际上时替某个对象调用它。

    成员函数通过一个名叫this的额外隐式参数来访问调用它的那个对象。当我们调用一个成员函数时,用请求该函数的对象地址初始化this。例如,如果调用的total.isbn()则服务器负责把total的地址传递给isbn的隐式形参this,可以等价地认为编译器将该调用重写了以下形式:

    //伪代码,用于说明调用成员函数的实际执行过程

    Sales_data::isbn(&total)

    其中,调用Sales_data的isbn成员时传入了total的地址。

    在成员函数内部,我们可以直接使用调用该函数的对象的成员,而无须通过成员访问运算符来做到这一点,因为this所指的正是这个对象。任何对类成员的直接访问都被看作时对this的隐式引用,也就是说,当isbn使用bookNo时,它隐式地使用this指向地成员,就像我们书写了this->boolNo一样。

    对于我们来说,this形参是隐式的,实际上,任何自定义名为this的参数或变量的行为都是非法的。我们可以在成员函数体内部使用this,因为,尽管没有必要,我们还是能把isbn定义为如下形式

    std::string isbn() const 
    {
      return this -> bookNo;
    }

    因为this的目的总是指向“这个”对象,所以this是一个常量指针,我们不允许改变this中保存的地址

    /***

    this1.cpp

    ***/

    #include<iostream>

    using namespace std;

    class Box

    {

        public:

            Box(){;}

            ~Box(){;}

            Box* get_address()

            {

                return this;

            }

    };

    int main()

    {

        Box box1;

        Box box2;

        Box* p = box1.get_address();

        cout << p << endl;

        p = box2.get_address();

        cout << p << endl;

        return 0;

    }

    exbot@ubuntu:~/wangqinghe/C++/20190807$ g++ this1.cpp -o this1

    exbot@ubuntu:~/wangqinghe/C++/20190807$ ./this1

    0x7fffb05ed946

    0x7fffb05ed947

    this指针的类型可以理解为Box*

    此时得到的两个地址分别为box1和box2对象的地址。

  • 相关阅读:
    k8s 资源管理
    Kubernetes核心组件
    python复习
    项目发布
    tornado
    斯巴达系统(一)
    Tornado-第三篇-tornado支持websocket协议
    Tornado-第二篇-异步非阻塞
    Tornado-第一篇-搭建网页
    python--面向对象的特殊方法(反射,内置方法)
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11316612.html
Copyright © 2011-2022 走看看