如何理解C ++隐含参数“this”

时间:2014-11-14 02:56:28

标签: c++

如果我们创建这样的类:

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

我们制作了一个对象;

Sales_data total;
total.isbn();

C ++ Primer,第五版,说(第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

然后,指针类型的用途是什么。

3 个答案:

答案 0 :(得分:3)

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

如果您使用visual studio或任何现代IDE,您可以检查 this 与其所属的类具有相同的类型。

有一本好书叫做#34; C ++对象模型&#34;由Stanley B. Lippman帮助理解。

答案 1 :(得分:1)

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

在C ++中,你可以

 object->function () ;

相反,在Ada中,语法是

function (object) ;

该对象是成员函数的显式参数。 this 变量是C ++成员调用语法的产物。而不是程序员必须显式声明一个标识对象的参数(如在Ada中),C ++会自动为你做这个(这个)。

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

答案 2 :(得分:0)

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

根据您的情况,它可能是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!
}