gpt4 book ai didi

c++ - 在C++中正确定义 “this”关键字?

转载 作者:行者123 更新时间:2023-12-02 09:50:26 25 4
gpt4 key购买 nike

我正在学习OOP C++编程背后的一些理论。我们的教授向我们提供了一些示例问题,以便我们可以在考试前进行修订。您能看看我对这个名词的理解是否正确吗?我真的很感谢您的任何建议。

The this keyword:
a) Inside a constructor, it is a reference to currently constructed object. (false)
b) In the method, it is a reference to the object for which it was called (true)
c) Inside the constructor it is a pointer to currently constructed object. (false)
d) In the method, it is a pointer to the object for which it was called. (false)

最佳答案

简单地说(这里不包括虚拟函数的复杂性):
this是一个指向构造对象的指针,这是传递给任何非静态成员函数的第一个参数。

例如

class X  { void foo() {} } ;
X x;

当您执行 x.foo()时,foo()的第一个不可见参数等于 &x。当您执行 x.foo()时,您实际上是在程序集级别执行 foo(&x)

从技术上讲,构造函数(在汇编级别)只是一个与任何其他成员函数一样的函数,唯一的区别是在对象构造上调用了它。它也像其他所有非静态成员一样使用this指针。

因此,您的问题c)和d)是正确的。

关于c++ - 在C++中正确定义 “this”关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60112311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com