C++ 中“this”指针的目的是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2828841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is purpose of a "this" pointer in C++?
提问by de costo
What is purpose of this
keyword. Doesn't the methods in a class have access to other peer members in the same class ? What is the need to call a this
to call peer methods inside a class?
this
关键字的目的是什么。一个类中的方法不能访问同一个类中的其他对等成员吗?什么需要调用 athis
来调用类内的对等方法?
回答by Josh Kelley
Two main uses:
两个主要用途:
To pass
*this
orthis
as a parameter to other, non-class methods.void do_something_to_a_foo(Foo *foo_instance); void Foo::DoSomething() { do_something_to_a_foo(this); }
- To allow you to remove ambiguities between member variables and function parameters. This is common in constructors.
(Although an initialization listis usually preferable to assignment in this particular example.)MessageBox::MessageBox(const string& message) { this->message = message; }
传递
*this
或this
作为参数传递给其他非类方法。void do_something_to_a_foo(Foo *foo_instance); void Foo::DoSomething() { do_something_to_a_foo(this); }
- 允许您消除成员变量和函数参数之间的歧义。这在构造函数中很常见。
(尽管在此特定示例中,初始化列表通常比赋值更可取。)MessageBox::MessageBox(const string& message) { this->message = message; }
回答by Martin York
- Helps in disambiguating variables.
- Pass yourself as a parameter or return yourself as a result
- 有助于消除变量的歧义。
- 将自己作为参数传递或作为结果返回自己
Example:
例子:
struct A
{
void test(int x)
{
this->x = x; // Disambiguate. Show shadowed variable.
}
A& operator=(A const& copy)
{
x = copy.x;
return *this; // return a reference to self
}
bool operator==(A const& rhs) const
{
return isEqual(*this, rhs); // Pass yourself as parameter.
// Bad example but you can see what I mean.
}
private:
int x;
};
回答by Justin Ethier
Consider the case when a parameter has the same name as a class member:
考虑参数与类成员同名的情况:
void setData(int data){
this->data = data;
}
回答by dlb
The expression *this
is commonly used to return the current object from a member function:
该表达式*this
通常用于从成员函数返回当前对象:
return *this;
The this
pointer is also used to guard against self-reference:
该this
指针也被用来防止自我参考:
if (&Object != this) {
// do not execute in cases of self-reference
回答by JohnMcG
- Resolve ambgiguity between member variables/functions and those defined at other scopes
- Make explicit to a reader of the code that a member function is being called or a member variable is being referenced.
- Trigger IntelliSense in the IDE (though that may just be me).
- 解决成员变量/函数与在其他范围定义的成员变量/函数之间的歧义
- 向代码的读者明确说明正在调用成员函数或正在引用成员变量。
- 在 IDE 中触发 IntelliSense(虽然这可能只是我)。
回答by Mohit Jain
Some points to be kept in mind
需要牢记的一些要点
This pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class.
This pointer is not counted for calculating the size of the object.
This pointers are not accessible for static member functions.
This pointers are not modifiable
该指针存储类实例的地址,使成员能够通过指针访问类的成员函数。
计算对象的大小时不计算该指针。
静态成员函数无法访问此指针。
此指针不可修改
Look at the following example to understand how to use the 'this' pointer explained in this C++ Tutorial.
查看以下示例以了解如何使用本 C++ 教程中解释的“this”指针。
class this_pointer_example // class for explaining C++ tutorial
{
int data1;
public:
//Function using this pointer for C++ Tutorial
int getdata()
{
return this->data1;
}
//Function without using this pointer
void setdata(int newval)
{
data1 = newval;
}
};
Thus, a member function can gain the access of data member by either using this pointer or not. Also read thisto understand some other basic things about this pointer
因此,成员函数可以通过使用或不使用此指针来获取数据成员的访问权限。另请阅读本文以了解有关此指针的其他一些基本内容
回答by Eclipse
It lets you pass the current object to another function:
它允许您将当前对象传递给另一个函数:
class Foo;
void FooHandler(Foo *foo);
class Foo
{
HandleThis()
{
FooHandler(this);
}
};
回答by Notinlist
For example if you write an operator=()
you must check for self assignment.
例如,如果你写了一个operator=()
你必须检查自赋值。
class C {
public:
const C& operator=(const C& rhs)
{
if(this==&rhs) // <-- check for self assignment before anything
return *this;
// algorithm of assignment here
return *this; // <- return a reference to yourself
}
};
回答by LukeN
The this
pointer inside a class is a reference to itself. It's needed for example in this case:
this
类内的指针是对自身的引用。例如在这种情况下需要它:
class YourClass
{
private:
int number;
public:
YourClass(int number)
{
this->number = number;
}
}
(while this would have been better done with an initialization list, this serves for demonstration)
(虽然这最好用初始化列表来完成,但这只是为了演示)
In this case you have 2 variables with the same name
在这种情况下,您有 2 个具有相同名称的变量
- The class private "number"
- And constructor parameter "number"
- 班级私人“号码”
- 和构造函数参数“编号”
Using this->number
, you let the compiler know you're assigning to the class-private variable.
使用this->number
,您可以让编译器知道您正在分配给类私有变量。
回答by Ignacio Vazquez-Abrams
It allows you to get around members being shadowed by method arguments or local variables.
它允许您绕过被方法参数或局部变量遮蔽的成员。