如何理解C++隐式参数"this"

  • 本文关键字:参数 this 何理解 C++ c++
  • 更新时间 :
  • 英文 :


如果我们创建一个这样的类:

class Sales_data
{
  std::string isbn() const {return bookNo;}
  std::string bookNo;
};

我们做一个对象总数;

Sales_data total;
total.isbn();

C++入门,第五版,说(第258页),"当我们调用成员函数时,this是用调用该函数的对象的地址初始化的",它是这样的:

Sales_data::isbn(&total)

而且书也写了,我们可以得到书没有像:

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

我认为隐式参数"this"就像一个指针,但是我看不到它的类型,有人会帮我指出我认为的错误以及我应该怎么做才能理解隐式参数"this"和这个参数的作用吗?

@Jason C我的额外问题:这是一个指针,所以它的行为就像一个普通的指针,

#include "iostream"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
  int a = 1;
  int * b = &a;
  cout << "the b is " << b << endl;
  cout << "the &a is " << &a << endl;
  cout << "the *b is " << *b << endl;
  cout << "the &b is" << &b << endl;
  return 0;
}

在我的计算机上,输出是:

the b is 0110FCEC
the &a is 0110FCEC
the *b is 1
the &b is0110FCE0

那么,指针的类型有什么用。

这不是

参数,而是对象引用自身的一种方式。

如果您使用 Visual Studio 或任何现代 IDE,则可以检查它是否与所属的类具有相同的类型。

斯坦利·B·利普曼(Stanley B. Lippman)有一本名为《C++对象模型》(The Object Model)的好书,可以帮助理解。

即使标准中没有这样定义,我所知道的每个实现都将其作为成员函数的隐式参数,并且可以这样查看。

在C++,你做

 object->function () ;

相比之下,在 Ada 中,语法是

function (object) ;

然后,该对象是成员函数的显式参数。this 变量是 C++ 的成员调用语法的产物。程序员不必显式声明标识对象的参数(如在 Ada 中),C++会自动为您执行此操作(this)。

在大多数实现中,C++参数绑定到堆栈上位置或寄存器的偏移量。这与其他参数(绑定到堆栈偏移或寄存器)的实现方式完全相同。

this

指向调用成员函数的任何对象实例的指针(请注意,在static成员函数或非成员函数中没有this)。

在您的情况下,它是Sales_data *,要么是const Sales_data *,具体取决于上下文。在isbn()里面,是后者。

这个(人为的)示例说明了它的价值:

class Example {
public:
    void function (Example *x);
};
void Example::function (Example *x) {
    if (x == this)
        cout << "x is this!" << endl;
    else
        cout << "x is not this." << endl;
}

现在,如果我们这样做:

Example a;
Example *b = new Example();
a.function(&a);  // outputs "x is this!"
b->function(b);  // outputs "x is this!"
a.function(b);   // outputs "x is not this!"
b->function(&a); // outputs "x is not this!"

此外,由于它是指向对象的"当前"实例的指针:

class Example2 {
public:
    int k;
    void function ();
};
void Example2::function () {
    k = 42; 
    this->k = 42; // does the same thing as above!
}

最新更新