如何理解C++隐式参数"this"
How to understand the C++ implicit parameter "this"
如果我们创建一个这样的类:
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!
}
- 了解'this'或其他参数是否为右值
- C++ Boost - 序列化错误 - 将"const B"作为"this"参数
- 成员函数的"this"参数具有"const"类型,但我的函数实际上不是"const"
- 整体模板参数。错误:在常量表达式中使用'this'
- 有没有办法绕过错误"因为'this'参数会丢弃限定符?
- 传递'const QVariant' 'this'参数会丢弃限定符 [-允许]
- C++错误:将"const umap_int {aka const std::unordered_map<int, int>}"作为"this"参数会丢弃限定符 [-permissive]
- 错误:将 x 作为 x 的参数传递'this'丢弃限定符
- C++ 不允许将'this'用作非类型模板参数
- const std::unordered_map<char, int>' 因为 'this' 参数会丢弃 lambda 中的限定符
- 为什么有必要将"this"指针作为"arg"参数传递给pthread_create
- 在模板类中使用"this"会导致参数初始化错误
- 错误:将“const sdf”作为“this”参数传递会丢弃限定符 [-fpermissive]
- 视觉C++:即使使用关键字,参数声明也会隐藏类成员"this"
- 错误:候选函数不可行:'this'参数具有类型 'const' 但方法未标记为 const
- 错误:将'xxx'作为'xxx'丢弃限定符的参数传递'this' [-允许]
- 用static_cast(*this)...初始化可变参数CRTP:<Base>合法吗?
- C++集合方法:函数'setCost'不可行:'this'参数的类型'const value_type'
- 如何理解C++隐式参数"this"
- C++:何时应该通过引用使用 PLUS 参数"this->"