【问题标题】:How to understand the C++ implicit parameter "this" [closed]如何理解 C++ 隐式参数“this”[关闭]
【发布时间】:2014-11-14 02:56:28
【问题描述】:

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

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

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

【问题讨论】:

  • 也许这anwser 有帮助。
  • 在您的情况下,它可以是 Sales_data *const Sales_data *,具体取决于上下文。在isbn()里面,是后者。
  • 这不仅仅是一个指针,它是一个指针。
  • 这个问题与primes无关,“我看不到可以存储对象地址的类型”是没有意义的。请用标准英语重述您的问题。
  • 抱歉,我已经删除了它,我会解释我的问题@Jason C

标签: c++


【解决方案1】:

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

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

Stanley B. Lippman 的一本好书叫做《The C++ Object Model》,可以帮助理解。

【讨论】:

    【解决方案2】:

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

    在 C++ 中,你可以这样做

     object->function () ;
    

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

    function (object) ;
    

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

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

    【讨论】:

      【解决方案3】:

      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!
      }
      

      【讨论】:

      • 实际上,在我的主要问题““我看不到可以存储对象地址的类型”是我想知道这个参数存储对象地址的位置,我尝试了一些简单的但还没弄清楚,我把它写在我的问题上。
      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 2018-09-09
      • 2010-10-31
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2015-01-01
      • 2012-10-08
      相关资源
      最近更新 更多